【发布时间】:2018-08-13 18:12:21
【问题描述】:
问题
我正在为我的朋友用 C++ 做一些代码注释,在一节中,我向我的朋友展示了三种不同的获取输入的方式。
在我的代码中,getline 写在第 14 行,cin 写在第 18 行。所以从逻辑上讲,应该首先评估 getline,但它没有。这是因为getline 比cin 慢吗?你能告诉我如何解决它吗?
如果你混淆了代码的格式,或者以任何你想要的方式添加新代码,我很好,但不要删除任何已经编写的代码来帮助我解决我的问题。
代码
第一种获取数字,第二种获取字符串,第三种获取多个值。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int userInputedAge;
cout << "Please enter your age: ";
cin >> userInputedAge;
string userInputedName;
cout << "Please enter your name: ";
getline(cin, userInputedName);
int userInputedHeight, userInputedFriendsHeight;
cout << "Please enter your height, and a friend's height: ";
cin >> userInputedHeight >> userInputedFriendsHeight;
}
这是输出。
Please enter your age: 13
Please enter your name: Please enter your height, and a friends height: 160
168
如您所见,我没有机会输入我对Please enter your name: 的答案,为什么?
【问题讨论】:
-
我无法正确理解会引发这样一个问题的想法混乱。
-
@LightnessRacesinOrbit cin w.r.t 的行为。行结束,然后是 getline w.r.t. 的后续行为。 OP 不理解行尾?
-
@davidbak:这是巴贝奇的一句话。
-
@LightnessRacesinOrbit - 我会查一下,谢谢!