初学者C ++输入behviour

时间:2016-12-10 18:12:41

标签: c++

这个程序在我的实践中是一个非常简单的代码来学习C ++。问题是在某些时候它不接受来自cin的输入并且行为奇怪。 程序的代码和输出如下。

为什么程序不考虑cin请“输入您的名字”?

enter image description here

# include "cmath"
# include <iostream>
using namespace std;

int main()
{
    string FirstName, MiddleName, LastName;
    string WelcomeMessage = "Welcome to Visual C++";
    int Number_of_Steps = 5;
    int LoopStart = 1, LoopEnd = 5;
    int AgeYears, AgeMonths;
    double Pi = 3.14;
    float k = 5.366;
    double Age;
    char* Symbol = "k"; 
    bool TestResult = true;

    MiddleName = "Milton";

    cout << "Input Your First Name and Last Name" << endl;
    cin >> FirstName >> LastName;
    cout << "Input your Age in Years" << endl; 
    cin >> AgeYears;
    cout << "Imput your Age in Months " << endl;
    cin >> AgeMonths;
    Age = AgeYears + AgeMonths / 12;
    cout << endl << "Your Name is " << FirstName << ' ' << LastName << endl;
    cout << "Your Age is " << Age << endl;
    cout << "The Character is " << Symbol << endl;

    // Testing operators
    cout << "Please Enter a floating point number \n";
    int n;
    cin >> n;
    cout << "n==" << n
        << "\n n+1==" << n + 1
        << "\n n three times==" << 3 * n
        << "\n n twice ==" << n + n
        << "\n nsquared ==" << n*n
        << "\n half of n ==" << n / 2
        << "\n square root of n ==" << sqrt(n)
        << "\n";    

    // Testing string addition
    cout << "Eneter your first name please" << endl;
    string String1, String2, String3;
    cin >> String1;
    cout << "Enter your family name please" << endl;
    cin >> String2;
    String3 = String1 + " " + String2;
    cout << "Welcome" << " " << String3 << endl;

    // testing inequalities to strings
    string FirstString, SecondString;
    cout << "Input First String "
        << endl;
    cin >> FirstString;
    cout << "Input Second String "
        << endl;
    cin >> SecondString;
    if (FirstString == SecondString)
        cout << "The two words are identical \n";
    if (FirstString >= SecondString)
        cout << "First word is bigger than second word \n";
    if (FirstString <= SecondString)
        cout << "Second word is bigger than first word \n";
}

1 个答案:

答案 0 :(得分:4)

您从显示.2的输出中获得提示作为名字(String1)。在询问名字之前cin操作在缓冲区上有64.2,但因为您将值读入int n,它只读取整数部分64并离开{{ 1}}在缓冲区上。如果你想要一个整数,将声明n更改为.2或进行一些输入验证,当你到达名字请求时,应该将缓冲区留空。