std :: ifstream在读取文件中的最后一项时将eofbit设置为点,但仅在读取数字类型时才会发生

时间:2018-09-28 22:11:11

标签: c++ fstream ifstream

假设给定一个包含数字列表的非空文本文件,

1 2 3 4 5

我们用std::ifstream将它们读入数字类型(intdouble等)以及char

int main()
{
    ifstream fs {"textfile.txt"};
    int val {0}; //read into ints
    for (int i{0}; i < 5; ++i)
    {
        //read five times
        fs >> val;
        cout << val << " is read. Current state of file stream: "
            << bitset<3> (fs.rdstate()) << endl; //check stream state after each read                        
    }
}

当读取为数字类型时,程序输出:

1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 010

在读取文件的最后一项时,设置了eofbit。

但是读char时不会发生同样的事情。

int main()
{
    ifstream fs {"textfile.txt"};
    char ch {0}; //read into chars
    for (int i{0}; i < 5; ++i)
    {
        //read five times
        fs >> ch;
        cout << ch << " is read. Current state of file stream: "
            << bitset<3> (fs.rdstate()) << endl; //check stream state after each read                        
    }
}

输出:

1 is read. Current state of fs: 000
2 is read. Current state of fs: 000
3 is read. Current state of fs: 000
4 is read. Current state of fs: 000
5 is read. Current state of fs: 000

为什么会这样?

1 个答案:

答案 0 :(得分:2)

读取EOF时会得到int,因为int的流提取运算符会尝试读取直到找到空白或不适合int的内容为止。因此,在读取了char之后,它将尝试读取另一个5,遇到文件末尾并且eofbit被设置。

相反,char的流提取运算符只会尝试读取一个char,因此不会遇到文件结尾。尝试从文件中读取6个char,您还将遇到EOF