Take the 2-minute tour ×

In C++, how do you handle wrong inputs? Like, if the program asks for an integer, when you type a character it should be able to do something and then loop to repeat the input but the loop goes infinite when you input a character when an integer is need and vice versa.

share|improve this question
add comment

4 Answers

up vote 4 down vote accepted

The reason the program goes into an infinite loop is because cin's bad input flag is set due to the input failing. The thing to do is to clear that flag and discard the bad input from the input buffer.

while (cout << "Enter a number" && !(cin >> num)) //executes loop if cin fails (like due to a bad input)
    cin.sync(); //discard unread characters in input buffer
    cin.clear(); //clear bad input flag
    cout << "Invalid input; please re-enter.\n";

See the Parashift C++ FAQ Lite for this, and other examples, including adding a minimum and/or maximum into the condition.

Another way would be to get the input as a string and convert it to an integer after checking it.

share|improve this answer
i have done some research before asking here. I saw that they put cin.ignore(1000, '\n'); what does this do? Also !(cin >> num) returns a boolean? i didn't know that –  Zik Apr 27 '12 at 11:42
thanks for the site –  Zik Apr 27 '12 at 11:48
@Marvin, cin.ignore (1000, '\n') ignores/discards characters in the input buffer until either 1000 have been discarded, or a newline has been encountered, whichever comes first. It's a good way to get rid of a line. You'll see in the parashift example, they use the maximum size of a stream instead of 1000 to account for a line of max length. I use cin.sync() because when doing this, I want to be on equal footing with the user (not read the next line yet), so I discard everything. Finally, cin has an operator void *, so it cann convert to a bool. –  chris Apr 27 '12 at 11:48
but how does the while loop check !(cin >> num) ? –  Zik Apr 27 '12 at 12:12
@Marvin, cin >> num fails if a user types, say 'a' when it was expecting an int. It provides a conversion operator to allow it to be implicitly converted to a void *. If cin is in a bad state, it will return NULL. If not, it will return the object. This can then be taken and converted to bool: true if not NULL, false if NULL. The loop can then use that to evaluate the bool expression it needs. –  chris Apr 27 '12 at 12:15
show 1 more comment

Test the input to see whether or not it is what your program expects. If it is not, alert the user that the input they provided is unacceptable.

share|improve this answer
add comment

Are you asking how to validate an integer input? If so, this has been asked before - try looking here

share|improve this answer
add comment

You can check it through the ASCII value if the ascii value s between 65 t0 90 or 97 to 122 the it would be character.

share|improve this answer
add comment

Your Answer


