【问题标题】:Beginner C++ input behviour初学者 C++ 输入行为
【发布时间】:2016-12-21 09:48:02
【问题描述】:

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

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

# 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";
}

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    【讨论】:

    • 感谢洛根的帮助 - 但请您进一步解释一下吗?
    • 换一种说法,当输入64.2 时,cin 将尽可能多地读取int(n 在您的代码中声明为int 而不是float )。 64int 有效,但它会在到达 . 时停止,因为 . 不是整数的一部分。
    • 非常感谢大家的帮助 - 在接下来的几个月里,Stack Overflow 肯定会成为我的故乡
    • 如果您对答案感到满意,您可以将其标记为正确,它会在它旁边打一个绿色的复选标记。这会给回答者一些声誉积分,并让其他人知道您的问题得到了充分的回应。
    • Stackoverflow 有大量现有答案,您可以搜索它们以找到答案,例如stackoverflow.com/a/16934374/5894196。如果搜索后没有找到您需要的答案,您可以提出一个新问题,但尽量避免提出重复的问题。
    猜你喜欢
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2011-08-13
    • 2012-04-14
    • 1970-01-01
    相关资源
    最近更新 更多