1

The function std::get() normally sets an eofbit when at the end of file. Since c++11 std::unget() first clears this bit and then proceds to unget last character read. What bothers me that after I reach eof, unget() doesn't seem to work for me, it only clears the bit but doesn't actually unget anything. Any subsequent calls to get() don't even set the eofbit again. Is this intentional, did I miss something in the documentation?

gcc version 6.3.1, -std=c++11

#include <iostream>
using namespace std;

int main ()
{
    while ( !cin . eof () )
        cout << " " <<  cin . get () << " ";
    cout << "end" << endl;
    cout << cin . eof () << endl;
    cout << (bool)cin . unget () << endl; 
    cout << cin . eof () << endl;
    cout << cin . get () << endl;
    cout << cin . eof () << endl;
    return 0;
}

example input foobar

example output

 102  111  111  98  97  114  10  -1 end
1
0
0
-1
0

What really bothers me is not that it puts back the -1 for eof, but why doesn't it set back eofbit after the last get()?

Ordoshsen
  • 518
  • 2
  • 13

1 Answers1

3

About the eofbit and failbit:

Reaching the End-of-File sets the eofbit. But note that operations that reach the End-of-File may also set the failbit if this makes them fail (thus setting both eofbit and failbit).

About the get():

Reads one character and returns it if available. Otherwise, returns Traits::eof() and sets failbit and eofbit.

Unget clears the eofbit, but cannot do anything with the failbit and thus fails too. Subsequent calls to get fail because of failbit being set and don't check for next character, because of which they can't set eofbit.

Ordoshsen
  • 518
  • 2
  • 13