Why does not seekg(0) clear the eof state of stream?

冷暖自知 提交于 2020-01-03 08:30:57

问题


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)?

EDIT:

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

回答1:


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

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

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

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

And a simple test:

#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
}



回答2:


Why not just manually clear() the stream then go back once the eofbit has been set? EOF has been reached, why should seekg clear it automatically? Doing that would seem to cause more problems.



来源:https://stackoverflow.com/questions/10141075/why-does-not-seekg0-clear-the-eof-state-of-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!