首页 > 解决方案 > 刚开始编写 C++

问题描述

我的代码中似乎有什么问题?

当我Enter输入年龄后点击时,提示已经结束,无需询问我的地址。我知道我可以使用getline()年龄,但如果用户输入非整数答案怎么办?

抱歉,我昨天才开始编码,我想学习基础知识。

#include <iostream>

using namespace std;

int main()
{
    int age;
    string name, address;

    cout << "Please enter the name of the user:" << endl;
    getline(cin, name);

    cout << "Please enter age of the user:" << endl;
    cin >> age;

    cout << "Please enter the address of the user:" << endl;
    getline(cin, address);

    cout << "Your name is " << name << " and you are " << age 
     << " years old " << " who lives in " << address << endl;

    cout << "Thank you for using my program!";


    return 0;
}

标签: c++

解决方案


只需在 'cin>>age' 之后添加 'cin.ignore()',如下所示:

cout << "Please enter age of the user:" << endl;
cin >> age;
cin.ignore();
cout << "Please enter the address of the user:" << endl;
getline(cin, address);

当 getline() 读取输入时,输入流中会留下一个换行符,因此它不会读取程序中的字符串(地址)。

如果用户在 age 中输入 'float' 或 'double' 等而不是 'int' ,那么它将简单地从中提取整数,例如:如果用户输入 39.29 或 39.00005 或 39.00 或然后 age=39

要了解有关 getline 的更多信息,请查看以下链接:


推荐阅读