6

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?

Izhido
  • 353
  • 3
  • 10

1 Answers1

4

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.

Stephen Kennedy
  • 16,598
  • 21
  • 82
  • 98
mr_beginner
  • 155
  • 8