istream defines a conversion to bool which indicates whether the last read was successful. You can use this to test whether parsing a double succeeded:
if (cin >> money) {
// success
} else {
// failure
}
If the stream is in a failed state and you want to retry reading—e.g., to prompt the user for a new value—then you can use the clear() member function to return the state to normal:
cin.clear();
However, this does not clear the input buffer, so you will end up reading the same data again. You can clear the input buffer until the next newline character:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Or you can read by lines instead, and use a stringstream to read individual values:
string line;
getline(cin, line);
istringstream stream(line);
if (stream >> money) {
// success
} else {
// failure
}
This has the advantage of forcing user input to be line-based—it’s token-based by default.
#include <iostream>//pre processor directive-<3.std::istreamprovides anoperator bool()that lets it be converted to a boolean.