C++eofbit相关的问题

不明白为什么eofbit是静态常量,书上还写没到末尾是0,到末尾置为1,静态常量根本无法修改啊,我使用cout测试,也一直都是1,值根本没变过

img

eofbit是std::ios_base::eofbit的别名,是一个标志位,定义在ios_base类中,表示文件流是否到达文件末尾。eofbit是一个静态常量,因为它的值在程序运行过程中是不会改变的,不需要通过修改来反映流的状态。
 
书上所说的“没到末尾是0,到末尾置为1”是指在使用文件流读取文件时,如果读取到文件末尾,则当读取操作试图读取文件时会设置eofbit标志位为1,表示文件已经到达末尾。如果读取的位置不在文件末尾,则eofbit标志位为0。
 
在使用std::ifstream等文件流对象的eof()函数时,会检查文件流的eofbit标志位是否为1,如果是1说明文件已经被读取到末尾。
因此,你在测试中一直输出为1是因为你的代码已经读取到了文件末尾,eofbit标志位已经被设置为1。如果文件没有到达末尾,则eofbit标志位为0

img


大家都在发


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    // 打开示例文件
    ifstream infile("foo.txt");
    if (!infile)
    {
        cerr << "Failed to open file\n";
        return 1;
    }

    // 检查 eofbit 标志位
    if (!infile.eof())
    {
        cout << "NOT End of file reached\n";
    }

    // 循环读取文件
    string line;
    while (getline(infile, line))
    {
        cout << line << endl;
    }

    // 再次检查 eofbit 标志位
    if (infile.eof())
    {
        cout << "End of file reached\n";
    }
    else
    {
        cout << "eofbit is set to 0\n";
    }

    infile.close();

    return 0;
}

跑跑看?