Sanity Checking User Input

Started by
2 comments, last by villiageidiot 18 years, 10 months ago
I was wondering what the best way to sanity-check user input is (using C++). For example, say a program requests the user to enter a number (1, 2, or 3) as a choice for a menu. What is the best way to check to make sure that the user has not entered something other than a number (like a string, or just random characters)? The trouble I have is that whenever I try to validate user input, I can always enter in some random collection of letters / numbers that causes the program to skip ahead or just crash altogether, which is a bad thing. Any advice?
Advertisement
Step-by-step!

1)read everything in as a string

2)Check to see if each element of the sring is in the form you want.

3)If string is not in the form you want go to step 1

4)Use stringstreams to enter the string as data into the variable

5)Profit

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

*bUrp* (not my usual burp, which has to do with source file organization, but an equally valuable bookmark)
Allright, thanks - I think I've got it now. Sorry for the stupid question...I ended up finding the answer a few minutes after I posted this. My bad!

This topic is closed to new replies.

Advertisement