user3477273
user3477273

Reputation:

cin infinite loop when reading in a non-numeric value

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

Upvotes: 1

Views: 992

Answers (2)

Ed Heal
Ed Heal

Reputation: 59997

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

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.

Upvotes: 2

Related Questions