What is the correct way to use cin.fail();
?
I am making a program where you need to input something. It is not very clear if you need to input a number or character. When a user inputs a character instead of a number the console goes crazy. How can I use cin.fail()
to fix this?
Or is there a better way?
std::cin.fail()
is used to test whether the preceding input
succeeded. It is, however, more idiomatic to just use the
stream as if it were a boolean:
if ( std::cin ) {
// last input succeeded, i.e. !std::cin.fail()
}
if ( !std::cin ) {
// last input failed, i.e. std::cin.fail()
}
In contexts where the syntax of the input permit either a number
of a character, the usual solution is to read it by lines (or in
some other string form), and parse it; when you detect that
there is a number, you can use an std::istringstream
to
convert it, or any number of other alternatives (strtol
, or
std::stoi
if you have C++11).
It is, however, possible to extract the data directly from the stream:
bool isNumeric;
std::string stringValue;
double numericValue;
if ( std::cin >> numericValue ) {
isNumeric = true;
} else {
isNumeric = false;
std::cin.clear();
if ( !(std::cin >> stringValue) ) {
// Shouldn't get here.
}
}