【问题标题】:Why does not seekg(0) clear the eof state of stream?为什么 seekg(0) 不清除流的 eof 状态?
【发布时间】:2012-04-13 12:43:55
【问题描述】:

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

编辑:

读者提供的以下程序在我的实现中给出了不同的结果( 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
}

上面的 cmets 来自在他的实现中尝试过该程序的用户。我得到了这些结果:

1 0
1 0
1 1
1 1

【问题讨论】:

  • 是的,您必须手动重置流的状态。
  • @Martin:似乎是旧标准与新标准的问题。

标签: c++ iostream


【解决方案1】:

根据标准clear()应该重置eofbit(§ 27.7.2.3):

basic_istream&lt;charT,traits&gt;&amp; seekg(pos_type pos);

效果: 表现为一个无格式的输入函数...,除了函数首先清除eofbit ...

但在标准(§ 27.6.1.3)中没有提到清除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
}

【讨论】:

  • 在您的第一个 foo.seekg(0) 之后,eofbit 在您的示例中被清除,而它仍在我的实现中。这就是为什么我要问一些奇怪的事情可能会发生。你的程序给出 1 0, 1 0, 1 1, 1 1
  • @Martin:好点。哪个编译器和什么环境?我得到了发布的结果:clang 3.1gcc 4.7.0gcc 4.6.3(有和没有-std=c++0x)。但是使用VS2010 我得到的结果和你一样。
  • 来自微软的有点陈旧的document 可能会对这个问题有所了解。 状态: 这种行为是设计使然。标准...?
  • 编译器是 Windows 的 gcc 端口,MinGW,带有适用于 Windows 的 Code::Block IDE 可执行文件:mingw32-c++.exe (TDM-2 mingw32) 4.4.1
【解决方案2】:

为什么不手动 clear() 流,然后在设置 eofbit 后返回?已达到EOF,为什么要自动清除它?这样做似乎会导致更多问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    相关资源
    最近更新 更多