User input of integers - error handling

I have problems with certain input areas of my program. There are several parts where the user enters a specific integer. Even if they enter the wrong option, but everything is wonderful and wonderful, but I noticed that if they enter something of a non-integer type, for example "m", this message will be repeated again.

I have a couple of functions that have integer input in them. Here is one for an example.

void Room::move(vector<Room>& v, int exone, int extwo, int exthree, int current) { v[current].is_occupied = false; int room_choice; cout << "\nEnter room to move to: "; while(true) { cin >> room_choice; if(room_choice == exone || room_choice == extwo || room_choice == exthree) { v[room_choice].is_occupied = true; break; } else cout << "Incorrect entry. Try again: "; } } 
+5
source share
3 answers

You can use cin.good() or cin.fail() to determine if cin can successfully handle the entered value. You can then use cin.clear() , if necessary, to clear the error state before processing continues.

+6
source

There is still a problem in your "resolved" code. Before checking the values, check the fail () check. (And, obviously, the problem is with eof () and IO errors as opposed to format problems).

Idiomatic reading

 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 } 
+10
source

For an even simpler way, you can use the operator ! in the following way:

  if ( !(cin >> room_choice) ) { cin.clear(); cin.ignore(); cout << "Incorrect entry. Try again: "; } 
+1
source

All Articles