fenris
fenris

Reputation: 49

Why is cin.failbit always set even when input is valid?

I was trying to write a program that asks to input a char array using cin.getline() and if given input is bigger than array length array gets extended.

I used cin.failbit to see if user's input was too long. But nothing went right. So after debugging I figured out that the problem lies in failbit.

So I wrote a simple program to see what was wrong about it and it turned out that somehow cin.failbit always returns true when in if-statement even when input seems valid.

int main () {
    char name[256];

    std::cout << "Enter your name: ";
    std::cin.getline (name,256, '\n');

    std::cout << "characters read: " << std::cin.gcount() << std::endl;
    if (std::cin.failbit){
        std::cin.clear();
        std::cout << "failed\n";
    }
} 

For example, when input is "qwer" program outputs that 5 characters have been read (cin.gcount), so it should be fine but it also outputs "fail" meaning that failbit flag is set. But I believe it shouldn't be in this case.

program output here

So can anyone explain why failbit appears to be set permanently?

Any help will be highly appreciated

Upvotes: 1

Views: 1121

Answers (1)

Fran&#231;ois Andrieux
Fran&#231;ois Andrieux

Reputation: 29022

std::cin.failbit is a constant that indicates which of the error bits represents stream failure. It is not an indication of the stream's current state. To check if that bit is set, use the member function std::cin.fail() instead.

However, if the stream failed to read due to reaching the end of the stream fail() will return false leading you to believe that it succeeded. Prefer std::cin.good() to check if the last operation succeeded.

Upvotes: 5

Related Questions