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?

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.

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.