Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

iostream

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
like image 944
Martin Avatar asked Apr 13 '12 12:04

Martin


1 Answers

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
}
like image 85
Anonymous Avatar answered Nov 13 '22 00:11

Anonymous