Sterilizing User Input

I'm trying to make sure that cin never gives me an error, no matter what the user inputs. This is what I have so far.

1
2
3
4
5
6
while(!(cin >> width))
                {
                    cin.clear();
                    cin.ignore(numeric_limits<streamsize>::max(), '\n');
                    cout << "Invalid input.  Try again: ";
                }


It works for letters, but if you enter "5r", it crashes. What else can I do?
is it type char? then it would overload
Sorry, yes, it is char. I want it to only allow numbers.
I don't know if you can change the behaviour somehow but normally when you read a char from std::cin you read a character and not a number. Can't you make width an int instead?
Oh god am I dumb... it is NOT a char, the variable width is an integer. The reason I posted this question is because it crashes whenever anything besides an integer is entered. I was trying to find a way to sterilize user input so that if they enter "octopus23" it gives an error as opposed to crashing while I am collecting the variable width.
When I said it works for letters, I meant that it successfully gives an error message when letters are inputted. However, I still get an error if letter/number combo's are inputted.

Sorry about the confusion.
Last edited on
When you enter "5r" it reads the integer value 5 into width so there no error. It probably crash because of something that happens after the loop.
Hm, you are right, it isn't crashing anymore.. I guess my problem is solved then heheh.
...this is embarassing
Last edited on
try string then string stream it into an int and test it for numbers then based on the reply give the error
Topic archived. No new replies allowed.