gpt4 book ai didi

c++ - std::ifstream 在读取文件中的最后一项时设置 eofbit,但它仅在读取数字类型时发生

转载 作者:行者123 更新时间:2023-11-28 01:28:50 24 4
gpt4 key购买 nike

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

1 2 3 4 5

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

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

为什么会这样?

最佳答案

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

相比之下,char 的流提取运算符只会尝试读取一个 char,因此它不会遇到文件末尾。尝试从文件中读取 6 个 char,您也会遇到 EOF

关于c++ - std::ifstream 在读取文件中的最后一项时设置 eofbit,但它仅在读取数字类型时发生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563223/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com