If >> fails (due to a string being where a number should be, for example), fail flag is set. Note that this flag can be checked with cin.fail() or simply evaluating cin to a boolean. To proceed with any other input, you need to clear that flag.
Your code could be
1 2 3 4 5 6 7 8 9
double n;
cout << "Please enter a number between 0 and 1: ";
while( !( cin >> n ) ){//this will be true if an error occurs. It could be while( cin.fail() )
//but then you'd have to add the actual input
string str;
cin.clear();//you need to clear the flags before input
getline( cin, str );//read what was written. Since you probably don't need this, look into cin.ignore()
cout << str << " is not a number\n";
}
I've got a similar problem. I have a program that has an array in it that is user inputted. The array is of int data type, and I need a way to validate that the data entered is an int for every iteration of the loop. Here's my loop. Just a basic for loop.
1 2 3 4 5
//get input
for(int x = 0; x < 10; x++)
{
cin >> pancakes[x];
}
In my program, if you enter a char or string into this, it just cuts out of the loop and outputs a bunch of huge ints. So I would like a way to check every loop if the data is an int, and if not allow the user to re enter the data for that part of the array. I've tried a couple things, none of them worked. :(
Thanks, but I have a question about this. How would >> fail? Let's say that a user entered "x" instead of a number. cin >> wouldn't fail, per se, it would accept the input and move along. It's me that would still have the same problem in that I have to go through all sorts of verifications to check whether this input is conforming or not.