[英]How to check EOF condition when using istream::ignore() function?
My test file contains just 2 characters: a
and \\n
: 我的测试文件仅包含2个字符:
a
和\\n
:
$ hexdump -C a.txt
00000000 61 0a |a.|
00000002
I want to test istream::ignore function: 我想测试istream :: ignore函数:
(1) I use ifs.ignore(2)
to skip a
and \\n
: (1)我使用
ifs.ignore(2)
跳过a
和\\n
:
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main() {
std::ifstream ifs("a.txt");
while (!ifs.eof())
{
std::cout << "Not end of file\n";
ifs.ignore(2);
}
return 0;
}
Test result is like this: 测试结果是这样的:
$ ./a.out
Not end of file
Program only enter loop once, and it fits my expectation. 程序只进入一次循环,符合我的期望。
(2) I use std::numeric_limits<std::streamsize>::max(), '\\n'
to skip a
and \\n
: (2)我使用
std::numeric_limits<std::streamsize>::max(), '\\n'
跳过a
和\\n
:
#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main() {
std::ifstream ifs("a.txt");
while (!ifs.eof())
{
std::cout << "Not end of file\n";
ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return 0;
}
But this time the program enters loop 2 time: 但是这次程序进入循环2次:
$ ./a.out
Not end of file
Not end of file
I can't understand this. 我听不懂 Per my understanding:
据我了解:
ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
should pass all characters, and ifs.eof()
should return true
the second time. 应该传递所有字符,并且
ifs.eof()
应该第二次返回true
。
std::basic_istream::ignore
will only set eofbit
if it encounters the end of the stream. std::basic_istream::ignore
遇到流的末尾,则只会设置eofbit
。 In your case, it instead encounters the \\n
, discards this, then returns without examining the stream further . 在您的情况下,它遇到
\\n
,将其丢弃,然后返回而无需进一步检查流 。 It has therefore not encountered the end of the stream in the first iteration, since it stops inspecting after extracting delim
; 因此,它在第一次迭代中就没有遇到流的末尾,因为它在提取
delim
之后停止检查。 for all it knows, there could be more data after the \\n
, because it hasn't tried to look at it yet. 就其所知,
\\n
之后可能会有更多数据,因为它尚未尝试查看它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.