C++: Check istream has non-space, non-tab, non-newline characters left without extracting chars
Posted
by
KRao
on Stack Overflow
See other posts from Stack Overflow
or by KRao
Published on 2011-02-06T14:38:26Z
Indexed on
2011/02/06
15:25 UTC
Read the original article
Hit count: 461
I am reading a std::istream and I need to verify without extracting characters that:
1) The stream is not "empty", i.e. that trying to read a char will not result in an fail state (solved by using peek() member function and checking fail state, then setting back to original state)
2) That among the characters left there is at least one which is not a space, a tab or a newline char.
The reason for this is, is that I am reading text files containing say one int per line, and sometimes there may be extra spaces / new-lines at the end of the file and this causes issues when I try get back the data from the file to a vector of int.
A peek(int n) would probably do what I need but I am stuck with its implementation. I know I could just read istream like:
while (myInt << myIstream) {...} //Will fail when I am at the end
but the same check would fail for a number of different conditions (say I have something which is not an int on some line) and being able to differentiate between the two reading errors (unexpected thing, nothing left) would help me to write more robust code, as I could write:
while (something_left(myIstream)) {
myInt << myIstream;
if (myStream.fail()) {...} //Horrible things happened
}
Thank you!
© Stack Overflow or respective owner