Avoid fail state of the input stream - inputting a char into an int!!
Posted on 2003-10-21
I am working on a Homework assignment and need this ASAP. I can email my professor but will not get an answer until the morning, most likely.
What is the common procedure to avoid entering the fail state of the input stream? I am writing a program, which is actually a simple game, and it depends on the user entering an integer value to be subtracted from an existing integer value. This is contained in a while loop, which runs until the remaining integer is 1.
How can I catch a user's mistake when he enters a non-integer like "a"? My professor mentioned something about validating using a char first, but then how would I even test to see if the char is an integer or not?
I know I can say if ( !istream ) then output an error.... or something like that... but of course now the input stream is in the fail state and the entire program must be restarted in order to restore that stream. Do I have everything correct? What should I do, besides just yelling at the user after he enters a character in place of an integer, and breaking the program, so that I can loop back and say hey you can't enter that, enter an integer now... without breaking that input stream.
Thanks in advance! Hopefully I have worded this clearly...