C ++中istream的效果 [英] eof of istream in C++
问题描述
bool ios::eof ( ) const;
根据库,
如果eofbit流的错误标志已由先前的I / O操作设置为
,则该函数返回true。当按与流关联的序列
到达文件末尾时,所有标准
输入操作均会设置此标志。
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();
}
我测试了2个文件,testcase1.txt和testcase2.txt。
I tested 2 files, testcase1.txt and testcase2.txt.
testcase1.txt是在终端中使用 cat
生成的,[Ctrl-D]用于结束输入:
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是在 vim
,我打开 vim
并输入 1.234
,然后保存并退出。
testcase2.txt was generated in vim
, I opened up vim
and just inputted 1.234
, and then saved and exited.
测试结果
测试结果为 testcase1.txt
是 1
,表示已设置 eofbit
,
Test result with testcase1.txt
is 1
, which means the eofbit
is set,
[~/C++ $] ./a.out testcase1.txt
1
带有 testcase2.txt
的测试结果为 0
,
[~/C++ $] ./a.out testcase2.txt
0
我同时打开 testcase1.txt
和 testcase2.txt
在 vim
中,它们看起来完全一样,然后为什么 eofbit $ c $没有为
testcase2.txt
设置c>?
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
?
推荐答案
您会在评论中看到一行新的内容:
As you see in comment, there is a new line:
ifstream ifs(argv[1]);
float f;
ifs >> f;
char c;
ifs.get( c ); // this will get '\n'
即使如此, EOF
仍然不会设置。...阅读您再次引用的段落:
Even so, the EOF
still won't set.... Read the paragraph you quoted again:
如果eofbit流的错误标志已由先前的I / O操作设置为
。当按与流关联的序列
到达文件末尾时,所有标准
输入操作均会设置此标志。
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.
要设置 eof
位,必须读取PASS的eof。您可以根据需要使用 peek()
进行操作。
To get the eof
bit set, you have to read PASS the eof. You can use peek()
to do it if you want.
ifstream ifs(argv[1]);
float f;
ifs >> f;
char c;
ifs.get( c ); // this will get '\n'
ifs.eof(); // this is false;
ifs.peek();
ifs.eof(); // this is true
另请参见: istream :: peek好奇行为举报。 EOF
这篇关于C ++中istream的效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!