Call putback () on istream multiple times

Many sites describe the function istream :: putback () , which allows you to "return" a character to the input stream so that you can read it again in a subsequent read operation.

What prevents me, however, from calling putback () several times in a row several times in the same thread? Of course, you should check for errors after each operation to see if it succeeded; and yet, I wonder: is there any guarantee that a particular type of stream supports the simultaneous addition of multiple characters?

I can only guess here, but I can imagine that istringstream can return as many characters as the length of a string in a stream; but I'm not sure if this is the same for ifstream .

It's true? How to find out how many characters I can putback () in istream ?

+4
source share
1 answer

If you want to read several characters from a stream, you can disable them using unget():

std::vector<char>&read_top5(std::istream & stream, std::vector<char> & container) {
    std::ios_base::sync_with_stdio(false);
    char c;
    int i=4;
    container.clear();

    while (stream && stream.get(c)) {
        container.push_back(c);
        if (--i < 0) break;
        if (c == '\n') break;
    }

    for (int j=0;j<(int)container.size();j++) {
        //stream.putback(container[j]); // not working
        stream.unget(); // working properly
    }

    return container;
}

This function reads the first 5 characters from the stream while they are still in the stream after the function exits.

+3
source

All Articles