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
}

Leave a Comment