Correct way to use cin.fail()

后端 未结 2 1756
广开言路
广开言路 2020-11-27 07:02

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

2条回答
  •  情歌与酒
    2020-11-27 07:26

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

提交回复
热议问题