读入非数值时的 cin 无限循环

cin infinite loop when reading in a non-numeric value

我在一个程序中有一个奇怪的行为,我花了很长时间试图推断原因。这是一个毫无意义的无限循环。测试这些代码行(怀疑)我得到了相同的结果。每次我输入一个非数字值这样的符号时,程序都会运行一个无限循环打印零,我猜这就是 cout 如何表示输入的错误值。我想知道为什么 cin 会出现这种奇怪的行为,打印所有这些零而不是在发现错误读数时停止。

#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    while(n >= 0) {
        cin >> n;
        cout << n << endl;
        }
    return 0;
}

the program runs through an infinite loop printing zeros, which i guess is how cout represents the wrong value entered.

这不太正确:当您向 cin 询问 int,但没有 int,您没有返回任何值,但无效输入仍保留在缓冲区中.当您在循环的下一次迭代中再次请求 int 时,同样的事情再次发生,并且没有取得任何进展:缓冲区中保留了错误数据。

这就是你得到无限循环的原因。要解决此问题,您需要添加一些代码以从输入缓冲区中删除错误数据。例如,您可以将其读入字符串,并忽略输入:

int n = 0;
while(n <= 0) {
    cin >> n;
    if (!cin.good()) {
        cin.clear();
        string ignore;
        cin >> ignore;
        continue;
    }
    cout << n << endl;
}

Demo.

您需要"eat"非数字输入即

#include <iostream>

using namespace std;

int main()
{
    int n = 0;
    while(n >= 0) {
        cin >> n;
        if (!cin) {
           char c;
           cin >> c;
        } else {
            cout << n << endl;
        }
    }
    return 0;
}