如何使用 istream::ignore() 函数时检查 EOF 条件



我的测试文件只包含 2 个字符:an

$ hexdump -C a.txt
00000000  61 0a                                             |a.|
00000002

我想测试 istream::ignore 函数:

(1(我用ifs.ignore(2)跳过an

#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main() {
    std::ifstream ifs("a.txt");
    while (!ifs.eof())
    {
        std::cout << "Not end of filen";
        ifs.ignore(2);
    }   
    return 0;
}

测试结果是这样的:

$ ./a.out
Not end of file

程序只进入循环一次,它符合我的期望。

(2(我用std::numeric_limits<std::streamsize>::max(), 'n'跳过an

#include <iostream>
#include <fstream>
#include <limits>
using namespace std;
int main() {
    std::ifstream ifs("a.txt");
    while (!ifs.eof())
    {
        std::cout << "Not end of filen";
        ifs.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    }   
    return 0;
}

但这次程序进入循环 2 次:

$ ./a.out
Not end of file
Not end of file

我无法理解这一点。根据我的理解:

ifs.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

应传递所有字符,ifs.eof()应第二次返回true

std::basic_istream::ignore只会在遇到流的末尾时设置eofbit。在您的情况下,它反而遇到了 n ,丢弃它,然后返回而不进一步检查流。因此,它在第一次迭代中没有遇到流的末尾,因为它在提取delim后停止检查;据它所知,n之后可能会有更多的数据,因为它还没有尝试查看它。

最新更新