how do I validate user input as a double in C++?
Solution 1:
Try this:
while (1) {
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while (cin.get() != '\n') ; // empty loop
}
}
This basically clears the error state, then reads and discards everything that was entered on the previous line.
Solution 2:
failbit
will be set after using an extraction operator if there was a parse error, there are a couple simple test functions good
and fail
you can check. They are exactly the opposite of each other because they handle eofbit
differently, but that's not an issue in this example.
Then, you have to clear failbit
before trying again.
As casablanca says, you also have to discard the non-numeric data still left in the input buffer.
So:
double x;
while (1) {
cout << '>';
cin >> x;
if (cin.good())
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
cin.ignore(100000, '\n');
}
}
//do other stuff...