std::cin 失败时的行为

Behavior of std::cin on failure

C++ 新手,我正在检查 cin 在意外输入时的行为并编写了以下代码

#include <iostream>

using std::cout;
using std::endl;
using std::cin;

int main() {
    
    int num = -1;

    cin >> num;
    cout << num << "\n";

    char alph = 'z';

    cin >> alph;
    cout << alph << "\n";

    return 0;
}

所以,它应该是一个数字,然后是一个字符。 以下是不同类型输入的结果

5 a
5
a
5a
5
a
aa
0
z

预计第一个。

在第二篇中,我读到 here 因为 std::cin 能够提取 5 操作将成功,将 a 留在缓冲区中。因此,a 被我们的字符输入。

第三种情况我看不懂。这里第一个 cin 提取失败。

然后呢?因为第二个 cin 没有做任何事情。 a 中的 none 是否留在缓冲区中。

您引用的 link 解释了正在发生的事情:

https://www.learncpp.com/cpp-tutorial/stdcin-and-handling-invalid-input/

When the user enters input in response to an extraction operation, that data is placed in a buffer inside of std::cin.

When the extraction operator is used, the following procedure happens:

  • If there is data already in the input buffer, that data is used for extraction.
  • If the input buffer contains no data, the user is asked to input data for extraction (this is the case most of the time). When the user hits enter, a ‘\n’ character will be placed in the input buffer.
  • operator>> extracts as much data from the input buffer as it can into the variable (ignoring any leading whitespace characters, such as spaces, tabs, or ‘\n’).
  • Any data that can not be extracted is left in the input buffer for the next extraction.

到目前为止,还不错。文章继续:

[Upon an input error] std::cin goes immediately into “failure mode”, but also assigns the closest in-range value to the variable. Consequently, x is left with the assigned value of 32767.

Additional inputs are skipped, leaving y with the initialized value of 0.

这解释了您看到的“0”。它还解释了为什么“z”没有替换为“a”。