Discussion:
istream::peek() now sets eof
(too old to reply)
Vladimir
2008-05-11 21:48:20 UTC
Permalink
Hi,
I just moved my project from C++ Builder 5 to Rad Studio 2007. The following
problem occured.
I have some overloaded istream >> operators for my classes. Some of them use
is.peek() to check the next character. If peek() returns eof, it doesn't
mean an input error in my case - it just means that my object is fully
extracted. In C++ Builder 5 peek() didn't change the state of a stream
(which seems reasonable to me), so that I could use is.good() to check the
success of the input operation. Like this:
is >> myint >> mywhatever >> my_using_peek_object;
if ( is.good() ) { ...success }
In Rad Studio peek() sets eof. Hence my check fails after successful
extraction. How can I work around this situation?
I tried the following:
int result = is.peek();
if ( /* result indicates, that I need stop extraction */ ) {
if ( is.eof() ) // in this special case I clear state manually
is.clear();
break; // stop extraction
}
The solution seems not good, because I can occasionally clear the real error
flags (?)
How can I clear eof flag and preserve other possible state flags? What
should be the correct expression for that?
Thank you.
Vladimir
unknown
2008-05-11 23:53:30 UTC
Permalink
Post by Vladimir
I have some overloaded istream >> operators for my classes. Some of them use
is.peek() to check the next character. If peek() returns eof, it doesn't
mean an input error in my case - it just means that my object is fully
extracted. In C++ Builder 5 peek() didn't change the state of a stream
(which seems reasonable to me), so that I could use is.good() to check the
is >> myint >> mywhatever >> my_using_peek_object;
if ( is.good() ) { ...success }
There might be a better C++ way to do this, such as throw(),
but take a look...

is >> myint >> mywhatever; //eof is error
if( is.good() )
{ is >> my_using_peek_object;
//use the data
}else{
break; // out of data
};
Post by Vladimir
In Rad Studio peek() sets eof. Hence my check fails after successful
extraction. How can I work around this situation?
If think if you check for eof first (don't peek if eof)
you might get better results.

Also, to preserve states, look at
iostate rdstate() const;
void setstate(iostate state);
Post by Vladimir
int result = is.peek();
if ( /* result indicates, that I need stop extraction */ ) {
if ( is.eof() ) // in this special case I clear state manually
is.clear();
break; // stop extraction
}
Loading...