Re: std::stringstream and eof() strangeness
carl.seleborg@gmail.com wrote:
I'm writing a lexer taking input from a character stream. For testing
purposes, I frequently use std::stringstream, since it's easy to get
the input I want to test my lexer with.
I expected something like this:
stringstream ss("");
assert (ss.eof());
eof() returns true set as soon as an operation(!) reached EOF. You didn't do
anything with that stream, so no the bit isn't set. I think you could try
the same with an empty file and it should behave the same.
But it turns out not to be true. However, this works:
stringstream ss("");
ss.peek();
assert (ss.eof());
I am surprised. This forces me to call peek() when I start lexing,
which I fell is a hack.
Hmmm, maybe you are writing your lexer the wrong way. What doesn't work is
this:
while(!in.eof()) {
in >> token;
use(token);
}
This rather has to be this:
while(in>>token) {
use(token);
}
Or, if you're working characterwise:
while(in.get(character)) {
use(character);
}
So since ss.peek() is not supposed to change the stream, how come
eof() returns different results?
It doesn't change the position in the input sequence, but that's all. After
all, it might require IO with an external device, so it must be allowed to
change things.
Uli
--
Sator Laser GmbH
Gesch?ftsf?hrer: Ronald Boers, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]