Question

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?

Était-ce utile?

La solution

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().

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top