简体   繁体   中英

eof of istream in C++

bool ios::eof ( ) const;

According to the library,

The function returns true if the eofbit stream's error flag has been set by a previous i/o operation. This flag is set by all standard input operations when the End Of File is reached in the sequence associated with the stream.

I wrote a program to run some tests:

int main(int argc, char *argv[])
{
    ifstream ifs(argv[1]);
    float f;
    ifs >> f;

    cout << ifs.eof() << endl; //check if eofbit set

    ifs.close();
}

I tested 2 files, testcase1.txt and testcase2.txt.

testcase1.txt was generated in the terminal with cat , [Ctrl-D] was used to end input:

[~/C++ $] cat > testcase1.txt
1.234[Ctrl-D]

testcase2.txt was generated in vim , I opened up vim and just inputted 1.234 , and then saved and exited.

Test Result

Test result with testcase1.txt is 1 , which means the eofbit is set,

[~/C++ $] ./a.out testcase1.txt
1

Test result with testcase2.txt is 0 ,

[~/C++ $] ./a.out testcase2.txt
0

I open both testcase1.txt and testcase2.txt in vim , they look exactly the same, then why the eofbit wasn't set for testcase2.txt ?

The vim is going to add a new line at the end of the file. That is why EOF is not reached.

As you see in comment, there is a new line:

ifstream ifs(argv[1]);
float f;
ifs >> f;
char c;
ifs.get( c ); // this will get '\n'

Even so, the EOF still won't set.... Read the paragraph you quoted again:

The function returns true if the eofbit stream's error flag has been set by a previous i/o operation . This flag is set by all standard input operations when the End Of File is reached in the sequence associated with the stream.

To get the eof bit set, you have to read PASS the eof. You can use peek() to do it if you want.

ifstream ifs(argv[1]);
float f;
ifs >> f;
char c;
ifs.get( c ); // this will get '\n'
ifs.eof();  // this is false;
ifs.peek();
ifs.eof(); // this is true

See also: istream::peek curious behavior wrt. EOF

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM