我的代码中似乎有什么问题?
输入年龄后,当我按 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;
}
答案 0 :(得分:1)
只需在“ 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()读取输入时,在输入流中会保留一个换行符,因为它不会读取程序中的字符串(地址)。
如果用户输入的是'float'或'double'等,而不是年龄为'int',则它将简单地从中提取整数, 例如: 如果用户输入39.29或39.00005或39.00或age = 39