[英]seekg() does not set eofbit when reaching EOF of a stream. Is it by design?
[英]Why does not seekg(0) clear the eof state of stream?
我想知道是否以及为什么seekg(0)
不应该清除流的eofbit
。 我已经阅读了所有的流,因此已达到EOF
(但尚未设置failbit
)并且想要将seekg()
到有效位置并再次读取一些字符。 在这种情况下, seekg(0)
似乎与eofbit
集合“工作”,但是一旦我尝试从流中读取,就会设置failbit。 这是逻辑,正确还是我的实施不好? 我是否应该认识到这种情况并手动清除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
}
以上评论来自在其实施中尝试该程序的用户。 我得到了这些结果:
1 0
1 0
1 1
1 1
根据新标准, clear()
应该重置eofbit
(§27.7.2.3):
basic_istream<charT,traits>& 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
}
为什么不只是手动清除()流然后在设置eofbit后返回? 已达到EOF,为什么要自动清除? 这样做似乎会导致更多问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.