User Input of Integers - Error Handling
There is still a problem in your "solved" code. You should check for fail() before checking the values. (And obviously, there is the problem of eof() and IO failure as opposed to format problems).
Idiomatic reading is
if (cin >> choice) {
// read succeeded
} else if (cin.bad()) {
// IO error
} else if (cin.eof()) {
// EOF reached (perhaps combined with a format problem)
} else {
// format problem
}
You can use cin.good()
or cin.fail()
to determine whether cin could successfully deal with the input value provided. You can then use cin.clear()
, if necessary, to clear the error state before continuing processing.
For a even simpler way, you can use !
operator like this:
if ( !(cin >> room_choice) )
{
cin.clear();
cin.ignore();
cout << "Incorrect entry. Try again: ";
}