Checking if the User Input is of correct type

If I make a program that requires an User Input, say of type Int, but the user inputs a character, the whole programme begins to loop infinitely.
Is there a way to prevent this from happening, like returning an Error Message that the input was invalid?
yes, there is a way to do it : )
And could you tell me what way is it?
Last edited on
Someone?
Well, I made a test app where I declared an int and did a cin>>. I then couted the int. I inputted a string of letters instead of an int. This is what cin placed in the int:

-858993460

I'm assuming this is an error code. Maybe you could run a similar experiment with your environment and see what the error code is and check for that in your program?

Of course, there's a problem if the user actually enters the error code. Another way to do it is to write a routine that getlines the input into a string. Then, you could look over the string character by character and check if all the characters are indeed numbers. If you allow negative numbers then you could allow a dash as the first character. I guess it would be up to you as to how to deal with spaces. After you have determined that it's a valid number, you could use a stringstream to convert the string to an int.
After you receive input, you can check the state of the stream with .good().
Topic archived. No new replies allowed.