【发布时间】:2019-07-24 02:52:09
【问题描述】:
我的代码中似乎有什么问题?
当我输入年龄后按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;
}
【问题讨论】:
-
您将
getline与cin >> whatever通话混在一起。这通常会导致疯狂。 -
getline从输入流中提取'\n',cin没有。在cin之后,'\n'仍保留在输入流中,并且由于getline只读取直到遇到'\n',它什么也不读取并且似乎跳到第二个getline提示符。 -
首先看看为什么要使用两种不同的输入方式:getline(cin, ) 和 cin>>?如果你能回答这个问题,你就会得到你的问题的答案。所以只要看看 getline 的文档就知道它和 cin 有什么不同了>>
-
您的问题已由上述副本回答。但是,作为这里的新用户,请使用tour 并阅读How to Ask!
-
见this answer我今天早些时候发布的另一个问题,它也可以应用于这个问题。
标签: c++