1

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;
}
  • `cin` is in an error state, you would know that if you checked it, but you don't. – Retired Ninja Feb 07 '15 at 09:38
  • 1
    possible duplicate of [Why does cin.clear() fix an infinite loop caused by bad input to cin?](http://stackoverflow.com/questions/13715131/why-does-cin-clear-fix-an-infinite-loop-caused-by-bad-input-to-cin) – Retired Ninja Feb 07 '15 at 09:39

2 Answers2

2

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

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;
}
Ed Heal
  • 59,252
  • 17
  • 87
  • 127