cin.eof() functionality

前端 未结 8 1175
夕颜
夕颜 2021-01-11 13:40

I understand that cin.eof() tests the stream format. And while giving input, end of character is not reached when there is wrong in the input. I tested

8条回答
  •  广开言路
    2021-01-11 13:53

    Assuming your input is line based, I suggest that you read the whole line using std::getline(). Once you have the line, you can analyse it and decide whether it contains correct or wrong input. Put the line into std::istringstream and do something like the following:

    Edit: Changed !! iss to static_cast(iss) for compatibility with C++0x.

    std::istringstream iss (line);
    char ch;
    long lval;
    // read the input
    iss >> lval;
    // result variable will contain true if the input was correct and false otherwise
    result
        // check that we have read a number of at least one digit length
        = static_cast(iss)
        // check that we cannot read anything beyond the value read above
        && ! (iss >> ch);
    

提交回复
热议问题