相关疑难解决方法(0)

ifstream的eof()如何工作?

#include <iostream>
#include <fstream>

int main() {
    std::fstream inf( "ex.txt", std::ios::in );
    while( !inf.eof() ) {
        std::cout << inf.get() << "\n";
    }
    inf.close();
    inf.clear();
    inf.open( "ex.txt", std::ios::in );
    char c;
    while( inf >> c ) {
        std::cout << c << "\n";
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我真的很困惑eof()功能.假设我的ex.txt的内容是:

abc
Run Code Online (Sandbox Code Playgroud)

它总是读取一个额外的字符,并-1在阅读时显示eof().但是inf >> c给出了'abc'的正确输出?任何人都可以帮我解释一下吗?

c++ ifstream eof

40
推荐指数
3
解决办法
13万
查看次数

标签 统计

c++ ×1

eof ×1

ifstream ×1