cin infinite loop when reading in a non-numeric value

那年仲夏 提交于 2021-02-02 08:38:15

问题


I had a strange behavior in a program and I spent long time trying to deduce why. it was an infinite loop with no sense. Testing these lines of code(under suspicion) i got the same result. Every time I type in a non-numeric value such a symbol, the program runs through an infinite loop printing zeros, which i guess is how cout represents the wrong value entered. I'd like to know why is that weird behavior from cin, printing all those zeros instead of stopping when it finds a wrong reading.

#include <iostream>

using namespace std;

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

回答1:


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

That is not quite right: when you ask cin for an int, but there's no int, you get no value back, but the invalid input remains in the buffer. When you ask for int again in the next iteration of the loop, same thing happens again, and no progress is made: bad data remains in the buffer.

That's why you get an infinite loop. To fix this, you need to add some code to remove bad data from the input buffer. For example, you could read it into a string, and ignore the input:

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

Demo.




回答2:


You need to "eat" the non-numerical input i.e.

#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;
}


来源:https://stackoverflow.com/questions/28380544/cin-infinite-loop-when-reading-in-a-non-numeric-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!