tellg, seekg, eof

tellg, seekg, eof

Post by dontwrit » Wed, 07 Apr 2004 16:25:30


Hi,
this question is about the iostream library.
It is sometimes good to save the position where you are in an istream
object and later return to that position. My problem is that it is only
possible if istream::eof() is false at the time of calling istream::seekg.
Is there some way to eliminate this? (Or some workaround or another
solution?)

Here is the example code:

----------------------------------------------
#include <iostream>
#include <strstream>
#include <string>
using namespace std;

void f(istream& in); // SEE BELOW

int _tmain(int argc, _TCHAR* argv[])
{
// A)
string strIn1("Hello this is me");
istrstream is1(strIn1.c_str());
f(is1);
cout << endl;
// B)
string strIn2("Hello this is");
istrstream is2(strIn2.c_str());
f(is2);

return 0;
}

void f(istream& in) {
string str;
in >> str; // "Hello"
cout << str << endl;
// SAVE WHERE IT STAYS:
istream::pos_type pos = in.tellg();
in >> str; // "this"
cout << str << endl;
in >> str; // "is"
cout << str << endl;
string str2;
// RETURN SAVED POSITION:
in.seekg(pos);
in >> str2; // "this" AGAIN
// BUT ONLY IF in.eof() IS FALSE
// OTHERWISE EMPTY STRING
cout << str2 << endl;
}//Test()

----------------------------------------------

The output:

Hello
this
is
this <- correct

Hello
this
is
<- empty string


In certain situations it does make sense to 'go back', regardless of the
EOF state of the stream. (E.g. when parsing a file you may have to 'read
forward'.)
So how could I somehow go back to a formerly saved position after EOF is
reached?

Thx,
Gus
 
 
 

tellg, seekg, eof

Post by tom_usene » Wed, 07 Apr 2004 18:44:16


clear()


in.clear();



When a stream enters an error state (such as EOF), you need to reset
the error state before you can perform any further operations,
including seeking. Call clear() to completely reset the error state,
but you should check errors carefully - make sure badbit isn't set in
robust code, and be aware of the meaning of failbit.

Tom
--
C++ FAQ: http://www.yqcomputer.com/ ++-faq-lite/
C FAQ: http://www.yqcomputer.com/ ~scs/C-faq/top.html