Issue
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%3E%3E/
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
Solution
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>>
reads1
,2
,3
into the buffer, then encounters Ctrl-Z, so it setseofbit
and stops reading.123
is then extracted from the buffer intonum
and the operator exits. At this point, the stream is not yet in an error state. When the stream'sbool
conversion is evaluated bywhile
, it returns true, allowing thewhile
body to be entered so it can processnum
.on the next iteration,
operator>>
seeseofbit
is set, preventing further reading. There is nothing left in the buffer to extract intonum
, so the operator setsfailbit
and exits. The stream is now in an error state. When the stream'sbool
conversion is evaluated bywhile
, it returns false, breaking thewhile
loop.
Answered By - Remy Lebeau