Home > Mobile >  Why is failbit set when I enter EOF?
Why is failbit set when I enter EOF?

Time:12-11

I'm currently learning how while (cin >> num) work and I found out that there are two steps. First one is the operator>> function return a istream object with error state, and the second is bool converter that convert istream object into bool depend on its state.

But I find it confusing that in the bool convert function, it will return 0 only if failbit or badbit is set. And the operator>> function will set eofbit if it read EOF.

bool convert function: https://www.cplusplus.com/reference/ios/ios/operator_bool/

operator>> function: https://www.cplusplus.com/reference/istream/istream/operator>>/

In this case, After I enter EOF the bool converter should return 1 because the failbit and badbit aren't set.

Therefore, I use the below program to check what actually happened to the error bit after I enter EOF. And I find out that the failbit will be set after entering EOF!!

So I'm wondering if anyone can help me understand why is failbit set?

#include <iostream>

using namespace std;

int main()
{
    int num;
    cin >> num;
    cout << cin.eof() << " " << cin.fail() << " " << cin.bad() << endl;
    return 0;
}

Input: ^Z(on windows using qt creator, non qt c project) Output: 1 1 0 Input: ^D(on windows using qt creator, non qt c project) Output: 0 1 0

CodePudding user response:

eofbit is set when a read operation encounters EOF while reading data into the stream's buffer. The data hasn't been processed yet.

failbit is set when the requested data fails to be extracted from the buffer, such as when reading an integer with operator>>. While waiting for digits to arrive, EOF could occur. eofbit alone is not enough to enter an error state, as there may be usable data in the buffer.

So, for example, imagine a while (cin >> num) loop is used and the user enters 123<Ctrl-Z>.

  • on the 1st iteration, operator>> reads 1, 2, 3 into the buffer, then encounters Ctrl-Z, so it sets eofbit and stops reading. 123 is then extracted from the buffer into num and the operator exits. At this point, the stream is not yet in an error state. When the stream's bool conversion is evaluated by while, it returns true, allowing the while body to be entered so it can process num.

  • on the next iteration, operator>> sees eofbit is set, preventing further reading. There is nothing left in the buffer to extract into num, so the operator sets failbit and exits. The stream is now in an error state. When the stream's bool conversion is evaluated by while, it returns false, breaking the while loop.

CodePudding user response:

If the EOF is the first input, the operator>> fails to read an integer, so the stream enters the fail() state.

If you type at least one digit before the Ctrl-Z, that digit is read and the input succeeds.

  • Related