为什么seekg(0)无法清除流的eof状态? [英] Why does not seekg(0) clear the eof state of stream?

查看:95
本文介绍了为什么seekg(0)无法清除流的eof状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否以及为什么不应该清除seekg(0)流的eofbit. 我已经读完所有流,因此已经达到了EOF(但尚未设置failbit),并且想返回seekg()到有效位置并再次读取一些字符.在这种情况下,seekg(0)似乎在eofbit设置下可以工作",但是一旦我尝试从流中读取,就设置了故障位.这是正确的逻辑还是我的实现不好?我是否应该识别这种情况并手动清除eofbit(如果未设置failbit)?

I would like to know if and why seekg(0) is not supposed to clear the eofbit of a stream. I am in a point where I have already read all the stream, thus EOF has been reached (but no failbit is set yet) and want to go back with seekg() to a valid position and read some chars again. In this case seekg(0) seems "to work" with the eofbit set, but as soon as I try to read from the stream, the failbit is set. Is this logic, correct or is my implementation bad? Am I supposed to recognize this case and clear the eofbit manually (if the failbit is not set)?

读者提供的以下程序在我的实现中给出了不同的结果(mingw32-c ++.exe(TDM-2 mingw32)4.4.1):

The following program provided by a reader gives different results in my implementation ( mingw32-c++.exe (TDM-2 mingw32) 4.4.1 ):

#include <sstream>
#include <iostream>
#include <string>

int main() {
        std::istringstream foo("AAA");
        std::string a;
        foo >> a;
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 1 0
        foo.seekg(0);
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 0 0
        foo >> a;
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 1 0
        foo >> a;
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 1 1
}

以上评论来自在其实现中尝试该程序的用户.我得到了这些结果:

The comments above are from the user who tried that program in his implementation. I obtain these results:

1 0
1 0
1 1
1 1

推荐答案

根据标准,clear()应该重置eofbit(第27.7.2.3节):

According to the new standard clear() is supposed to reset the eofbit (§ 27.7.2.3):

basic_istream<charT,traits>& seekg(pos_type pos);

效果:表现为未格式化的输入函数...,只是函数首先清除了eofbit ...

Effects: Behaves as an unformatted input function ..., except that the function first clears eofbit ...

但是在标准(第27.6.1.3节)中,没有提到清除eofbit

But in the old standard (§ 27.6.1.3) there is no mention of clearing the eofbit!

一个简单的测试:

#include <sstream>
#include <iostream>
#include <string>

int main() {
        std::istringstream foo("AAA");
        std::string a;
        foo >> a;
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 1 0
        foo.seekg(0);
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 0 0
        foo >> a;
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 1 0
        foo >> a;
        std::cout << foo.eof() << " " << foo.fail() << std::endl; // 1 1
}

这篇关于为什么seekg(0)无法清除流的eof状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆