tags:

views:

304

answers:

4

I'm doing a read in on a file character by character using istream::get(). How do I end this function with something to check if there's nothing left to read in formatted in the file (eg. only whitespace) and set the corresponding flags (EOF, bad, etc)?

A: 

How do I end this function with something to check if there's nothing left to read in formatted in the file (eg. only whitespace)?

Whitespace characters are characters in the stream. You cannot assume that the stream will do intelligent processing for you. Until and unless, you write your own filtering stream.

dirkgently
Yes, what i'm asking is basically how can I set the same things as a formatted read (using >>) does after it is called, where, if I have a file with a string and then 20 newlines, it will set the EOF flag after reading in the string?
Stuart P. Bentley
Newlines are characters too. I think I have given you the answer.
dirkgently
No, see, if I have a file with the contents"String" and i dostring TakenIn;FileWithNewlines>>TakenIn;FilewithNewlines.eof(); //this will return true
Stuart P. Bentley
There's supposed to be a bunch of newlines after that string, but any whitespace will do.
Stuart P. Bentley
If you know the number of strings, set eofbit to true after you have read all your strings.
dirkgently
I don't, that's the point. I'm trying to set eofbit to true after the file is devoid of anything but whitespace, where any additional formatted reads using >> will set eofbit. I'm trying to set eofbit in this fashion without actually doing a read in.
Stuart P. Bentley
A: 

Use istream::sentry.

Stuart P. Bentley
A: 

By default, all of the formatted extraction operations (overloads of operator>>()) skip over whitespace before extracting an item -- are you sure you want to part ways with this approach?

If yes, then you could probably achieve what you want by deriving a new class, my_istream, from istream, and overriding each operator>>() to call the following method at the end:

void skip_whitespace() {
    char ch;
    ios_base old_flags = flags(ios_base::skipws);
    *this >> ch;    // Skips over whitespace to read a character
    flags(old_flags);

    if (*this) {    // I.e. not at end of file and no errors occurred
        unget();
    }
}

It's quite a bit of work. I'm leaving out a few details here (such as the fact that a more general solution would be to override the class template basic_istream<CharT, Traits>).

j_random_hacker
A: 

istream is not going to help a lot - it functions as designed. However, it delegates the actual reading to streambufs. If your streambuf wrapper trims trailing whitespace, an istream reading from that streambuf won't notice it.

MSalters