这个问题在这里已有答案:
题
我正在用C ++为我的朋友制作一些代码注释,在一节中,我向朋友展示了三种不同的输入方式。
在我的代码中,我在第14行写了getline
,在第18行写了cin
。从逻辑上讲,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:
的答案为什么?
这与评估顺序无关,并且代码行不会在运行时随机切换位置。
当系统提示您输入年龄时,您输入了一个数字,然后按Enter键。当然,你这样做是有充分理由的 - 这是向终端发出信号的唯一方式,它应该发送到目前为止你输入的内容。
但是,该输入包含一个实际字符(可能是换行符,也可能是回车符),它仍然在缓冲区中。这导致下一个输入操作getline
立即完成。它读了一个空行。