-
Data Validation?
Is there a way in C++ to validate user data for lack of a better term?
For instance I want to write a program that asks a user for numeric input do some calculations on that data and then ask if the user wants to quit.. Since my code would be expecting numeric input what would be the best way to input a sentinal? I was thinking "Q" to quit but that would genereate an error if the program is expecting numeric right?
int firstNum,secNum;
cout<<"This program runs in a loop enter Q to quit"<<endl;
cout<<"Enter your first number"<<endl;
cin>>firstNum
cout<<"Enter 2nd number"<<endl;
cin>>secNum;
etc etc
since firstNum would be expecting data type of int if a user enters Q it woldn't work correct?
-
If the user enters Q your program is just hosed. If you are concerned about data validation, read into a string (or stringstream), and then read out of that string(stream) if possible.
-
You can read in a line of text using getline. You can compare this text to whatever you want, including "Q" or "quit" or any other text that can be typed before hitting enter. If you are expecting a number (for example, after you have determined that the input is not "Q"), then you can place the string in a stringstream as tabstop suggested.
There are other ways to do simple input validation, including checking the return value of the read operation when you read in the number. However, those solutions would not allow you to accept either "Q" or a number, so using getline and a stringstream is probably your best bet for this.
-
Hmm so maybe I'd be better off using a sentinel like "9999" to quit... I'm a beginner as I've mentioned in previous posts and stringstream isn't familiar to me.
Or would it be possible to enter a negative number? would C++ take a value of say -99 as input? Just kind of thinking out loud here...
Thanks for the replies guys.... very much appreciated!
-
Yes... a negative number is often used and makes sense. If the actual numbers the user enters should never be negative, then just use -1 to quit. People do it all the time.
If they're allowed to enter negative numbers for real data, then it is harder. You should probably define what the valid numbers are for them to enter and pick a number outside that range.
Note that if the user types 'q' or any other letter with your current code, the program will break. You can do extra data validation that doesn't involve stringstreams to avoid that, but it all depends on how much error checking you want to add.