문제

while(cin.fail()){

    cout<<"Error: Your line is too long.\nPlease enter a shorter line: ";
    cin.clear(cin.good());
    cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    cin.getline(name, maxCh);
}

I'm using cin.clear(cin.good()); to clear the error flags

But using cin.clear(); also works?, if I'm calling this function, what good does putting cin.good() do?

도움이 되었습니까?

해결책

For starters, I'm not sure that std::cin.clear( std::cin.good() ) is even guaranteed to compile. std::cin.good() returns a bool, std::cin.clear() requires an std::ios_base::iostate, and I'm not sure that there is guaranteed to be a conversion. (std::ios_base::iostate could be an enum, for example.) Second, even if it compiles, it only does what you want by accident: because you only execute this code if std::cin.fail() is true, std::cin.good() will return false, which will convert to 0 for all integral types, and std::ios_base::goodbit (which is probably what you want) is defined to be 0. It's also the default argument for the function, so there's really no point in specifying it. (clear can be used to set bits, but it's very brutal in the way it does so; usually, when you want to set an error, you'll use setstate, which will not reset any existing errors.)

For what it's worth: I've never found a case where it would be appropriate to call std::basic_ios<>::good().

다른 팁

If cin.good() returns true then you are actually setting the eofbit (depending on implementation) with your call to clear. Otherwise you are setting it to goodbit.

If you don't call cin.clear with a parameter, then it will use the default which is goodbit.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top