Correct way to use cin.fail()

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.
    }
}

Leave a Comment