ifstream eof 函数 (C++)

use*_*243 1 c++ file ifstream eof

我有这个代码:

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"
Run Code Online (Sandbox Code Playgroud)

以及文件“a.txt”,其中没有任何内容。

输出是“不”,总是“不”。我不明白。。我用错了吗?

编辑:仍然 .eof() 不起作用

0x4*_*2D2 5

std::basic_istream<...>::eof()仅当最近的提取在流状态中设置了适当的位时才返回 true。当构建文件流时,其流状态始终是 的流状态std::ios_base::goodbit

另一种方法是检查下一个可用字符是否是 EOF 字符:

if (f.peek() == std::char_traits<char>::eof())
Run Code Online (Sandbox Code Playgroud)