C++ 中 istream 的 eof
bool ios::eof ( ) const;
据图书馆称,
如果 eofbit 流的错误标志已被设置,则该函数返回 true 由先前的 i/o 操作设置。该标志由所有标准设置 当到达序列中的文件结尾时的输入操作 与流关联。
我编写了一个程序来运行一些测试:
int main(int argc, char *argv[])
{
ifstream ifs(argv[1]);
float f;
ifs >> f;
cout << ifs.eof() << endl; //check if eofbit set
ifs.close();
}
我测试了 2 个文件,testcase1.txt 和 testcase2.txt。
testcase1.txt是在终端用cat
生成的,[Ctrl-D]用于结束输入:
[~/C++ $] cat > testcase1.txt
1.234[Ctrl-D]
testcase2.txt是在vim
中生成的,我打开了vim
,输入1.234
,然后保存退出。
测试结果
testcase1.txt
测试结果为1
,表示eofbit
已设置,
[~/C++ $] ./a.out testcase1.txt
1
测试结果< code>testcase2.txt 是 0
,
[~/C++ $] ./a.out testcase2.txt
0
我在 vim
中打开 testcase1.txt
和 testcase2.txt
code>,它们看起来一模一样,那为什么未为 testcase2.txt
设置 eofbit
?
bool ios::eof ( ) const;
According to the library,
The function returns true if the eofbit stream's error flag has been
set by a previous i/o operation. This flag is set by all standard
input operations when the End Of File is reached in the sequence
associated with the stream.
I wrote a program to run some tests:
int main(int argc, char *argv[])
{
ifstream ifs(argv[1]);
float f;
ifs >> f;
cout << ifs.eof() << endl; //check if eofbit set
ifs.close();
}
I tested 2 files, testcase1.txt and testcase2.txt.
testcase1.txt was generated in the terminal with cat
, [Ctrl-D] was used to end input:
[~/C++ $] cat > testcase1.txt
1.234[Ctrl-D]
testcase2.txt was generated in vim
, I opened up vim
and just inputted 1.234
, and then saved and exited.
Test Result
Test result with testcase1.txt
is 1
, which means the eofbit
is set,
[~/C++ $] ./a.out testcase1.txt
1
Test result with testcase2.txt
is 0
,
[~/C++ $] ./a.out testcase2.txt
0
I open both testcase1.txt
and testcase2.txt
in vim
, they look exactly the same, then why the eofbit
wasn't set for testcase2.txt
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您在评论中看到的,有一个新行:
即使如此,
EOF
仍然不会设置....再次阅读您引用的段落:要设置
eof
位,您必须读取 PASS eof。如果需要,您可以使用peek()
来执行此操作。另请参阅:istream::peek 好奇行为。 EOF
As you see in comment, there is a new line:
Even so, the
EOF
still won't set.... Read the paragraph you quoted again:To get the
eof
bit set, you have to read PASS the eof. You can usepeek()
to do it if you want.See also: istream::peek curious behavior wrt. EOF
vim 将在文件末尾添加一个新行。这就是未达到 EOF 的原因。
The vim is going to add a new line at the end of the file. That is why EOF is not reached.