为什么 std::cin 没有从头开始阅读

why is std::cin not reading from the start

我在看一个涉及 std::cin 如何工作的问题。这是问题:

如果以下程序在要求您输入时键入两个名字(例如 Samuel Beckett),它会做什么?

#include <iostream>
#include <string>

int main() {

    std::cout << "What is your name? ";
    std::string name;
    std::cin >> name;
    std::cout << "Hello, " << name << std::endl << "And what is yours? ";

    std::cin >> name;
    std::cout << "Hello, " << name << std::endl << "; nice to meet you too!" << std::endl;

    return 0;
}

我预计输出为:

What is your name? Samuel Beckett
Hello, Samuel
And what is yours? Hello, Samuel
; nice to meet you too!

但是输出是:

What is your name? Samuel Beckett
Hello, Samuel
And what is yours? Hello, Beckett
; nice to meet you too!

有人可以帮忙吗,std::cin 工作得怎么样?

我知道如果我这样做:

    std::string a, b;
    std::cin >> a >> b;

并输入两个词,然后 a 将有第一个词, b 将有 second.But 为什么会这样? std::cin 难道不应该首先丢弃所有空格然后读取字符直到到达另一个空格吗???

非常感谢任何帮助。

流提取器 (>>) 以空格分隔 - 当它读取时,它会在遇到任何空格时停止。下次使用它时,它会从停止的地方开始读取。如果您只想在换行符上定界,则可以改用 cin.getline()

编辑:来自@Pete Becker 的更正。

What does the following program do if, when it asks you for input, you type two names (for example Samuel Beckett)?

operator>> 在遇到空格(以及其他情况)时停止读取。因此,第一次调用 >> return 仅 Samuel,将 Beckett 留在输入缓冲区中以供下一次调用 >> 至 return .这正是您看到的情况。

I know that if i do this:

std::string a, b;
std::cin >> a >> b;

and type two words in, then a will have the first word and b will have the second.

没有任何区别
std::cin >> a >> b;

std::cin >> a;
std::cin >> b;

在第一种情况下,operator>> return 是对正在读取的流的 std::istream& 引用,这允许将多个操作链接在一起。但是同样的操作也可以在单独的语句中完成。

Isn't std::cin supposed to initially discard all whitespace first and then read characters till another whitespace is reached???

不是 std::cin 本身,而是 operator>>,但是是的,这正是这里发生的事情。