为什么 cin 在 getline 之前进行评估,即使 cin 在 getline 之后



问题

正在C++为我的朋友做一些代码笔记,在一节中,我向我的朋友展示了三种不同的输入方式。

在我的代码中,我getline写在第 14 行,cin写在第 18 行。所以从逻辑上讲,getline应该首先进行评估,但事实并非如此。这是因为getlinecin慢吗?你能告诉我如何解决它吗?

如果您混淆代码的格式,或者以您想要的任何方式添加新代码,我很好,但不要删除任何已经编写以帮助我解决问题的代码。

法典

第一种方法是获取数字,第二种方法是获取字符串,第三种方法是获取多个值。

#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:为什么?

这与计算顺序无关,代码行不会在运行时随机切换位置。

当系统提示您输入年龄时,您输入了一个数字,然后按回车键。当然,您这样做是有充分理由的 - 这是向您的终端发出信号的唯一方法,它应该发送您到目前为止键入的内容。

但是该输入由仍在缓冲区中的实际字符(可能是换行符,也可能是回车符(组成。这将导致下一个输入操作(getline(立即完成。它读取了一个空行。

使代码跳过该换行符。

最新更新