Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling putback() on istream multiple times

Tags:

c++

istream

Many sites describe the istream::putback() function that lets you "put back" a character into the input stream so you can read it again in a subsequent reading operation.

What's to stop me, however, from calling putback() multiple times in sequence over the same stream? Of course, you're supposed to check for errors after every operation in order to find out if it succeeded; and yet, I wonder: is there any guarantee that a particular type of stream supports putting back more than one character at a time?

I'm only guessing here, but I can imagine istringstream is able to put back as many characters as the length of the string within the stream; but I'm not so sure that it is the same for ifstream.

Is any of this true? How do I find out how many characters I can putback() into an istream?

like image 208
Izhido Avatar asked Mar 25 '16 03:03

Izhido


People also ask

What is cin putback() c++?

Put character back. Attempts to decrease the current location in the stream by one character, making the last character extracted from the stream once again available to be extracted by input operations.

What is the C++ stream function that puts a read character back to a stream?

The ungetc() function in C++ push the previously read character back to the stream so that it could be read again. The ungetc() function is defined in <cstdio> header file.


1 Answers

If you want to read multiple characters from a stream you may unget 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 stream while they are still in stream after the function exits.

like image 105
mr_beginner Avatar answered Oct 12 '22 04:10

mr_beginner