c++ - cin infinite loop when reading in a non-numeric value -


i had strange behavior in program , spent long time trying deduce why. infinite loop no sense. testing these lines of code(under suspicion) got same result. every time type in non-numeric value such symbol, program runs through infinite loop printing zeros, guess how cout represents wrong value entered. i'd know why weird behavior cin, printing zeros instead of stopping when finds wrong reading.

#include <iostream>  using namespace std;  int main() {     int n = 0;     while(n >= 0) {         cin >> n;         cout << n << endl;         }     return 0; } 

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

that not quite right: when ask cin int, there's no int, no value back, invalid input remains in buffer. when ask int again in next iteration of loop, same thing happens again, , no progress made: bad data remains in buffer.

that's why infinite loop. fix this, need add code remove bad data input buffer. example, read string, , ignore input:

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

demo.


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -