简体   繁体   中英

ifstream eof function (C++)

I have this code:

string a = "D:\\Users\\user-pc\\Desktop\\testing\\a.txt";

ifstream f;
    /*edit*/ string line;

    /*edit*/ getline(f, line);
f.open(a);
if ( f.eof() )
    cout << "ended";
else
    cout << "nope"

and the file 'a.txt' which has nothing in it.

the output is nope, alway nope. I don't get it.. Do I use it wrong?

EDIT: still .eof() not working

std::basic_istream<...>::eof() only returns true if a recent extraction set the appropriate bit in the stream state. When a file stream is constructed, its stream state is always that of std::ios_base::goodbit .

An alternative is to check if the next available character is the EOF character:

if (f.peek() == std::char_traits<char>::eof())

只有在读取尝试读取文件末尾之后才设置eofbit错误状态标志。

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