c++ - Why does this code end up in an infinite loop, reading from std::cin -
hi try create input function function through vector.
however, don't know why input become infinite loop?
do { cout << "please enter next number: "; cin >> num; number.push_back(num); cout << "do want end? enter 0 continue."; dec = null; cin >> dec; } while(dec == 0);
"i don't know why input become infinite loop."
the reason can imagine is, incorrect input sets cin
fail
state. in case (e.g. invalid number entered, or enter pressed) cin
set fail
state , value in dec
won't change evermore. once cin
in fail
state subsequent input operations fail respectively, , subject input won't changed.
to proof against such behavior, have clear()
std::istream
's state, , read safe point, before proceeding (see also: how test whether stringstream operator>> has parsed bad type , skip it):
do { cout << "please enter next number: "; if(cin >> num) { number.push_back(num); } else { cerr << "invalid input, enter number please." << std::endl; std::string dummy; cin.clear(); cin >> dummy; } cout << "do want end? enter 0 continue."; dec = -1; if(!(cin >> dec)) { std::string dummy; cin.clear(); cin >> dummy; break; // escape loop if other 0 // typed in } } while(dec == 0);
here 3 working demos different inputs end loop:
1 0 2 0 3 0 4
enter
1 0 2 0 3 0 4 xyz
1 0 2 0 3 0 4 42
the loop finite, , output of above
1234
should note have changed bool dec;
int dec;
, that's minor point.
Comments
Post a Comment