Can anyone help me with a bit of code that will validate the input from a user? I know that cin.fail() works for most cases, i.e.
1 2 3 4 5 6 7 8 9 10 11
float i;
cout << "please enter a number\n";
cin >> i;
if(cin.fail())
{
cout << "you did not enter a number\n";
}
else
{
cout << "your number is: "<< i << endl;
}
So with the above if someone enters 'bob' when asked for the number the program will tell the user that they did not enter a number. However is the user enters '5bob' the error will not be caught. I know the code above is rather sloppy, but I just wanted to give a quick example. If anyone can help I would appreciate it. Thanks!
Get the entire input into a string, then use a stringstream to get it out (essentially what you are doing there). But since you have a stringstream, you can check to see if there is still data left to be read. If there is, there is a problem.