c++ - Why does this do while loop repeat infinitely? -


i want prompt user input integer, if user enters non-integer, program should keep demanding integer until user complies.

int getinteger(){     int input;      do{         std::cout << "enter integer: ";         std::cin >> input;     } while(!(std::cin));       return input; } 

if user enters integer, function returns it.

but if user enters "hello," function goes on infinite, cout-ing "enter integer: ".

how fix this?

!(std::cin) 

will evaluate true if std::cin in bad state, e.g. after input operation failed. then, subsequent input operations fail , not change cin's error state, infinite loop.

to behavior want, may use like

while (!(std::cin >> input)) {     std::cout << "try again\n";     // clear away error state     std::cin.clear();             // ignore ever garbage still in stream     std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  } 

in real world, may want handle (generally not recoverable) failures eof (someone sent end of file character) , bad (cin broken, should not happen) different fail happens after invalid input. is, example, shown on this reference page ignore. however, should not bite in toy programs yours seems be.


Comments