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

Why does cin evaluate before getline even though cin comes after getline?

问题

我正在用 C++ 为我的朋友做一些代码笔记,并且在一个部分中,我向我的朋友展示了三种不同的获取输入的方法。

在我的代码中,我在第 14 行写了 getline,在第 18 行写了 cin。所以从逻辑上讲,应该先计算 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: 的回答,为什么?

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

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

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

Make your code skip that newline.