Namespaces
Variants
Views
Actions

std::basic_istream::putback

From cppreference.com
basic_istream& putback( char_type ch );

Puts the character ch back to the input stream so the next extracted character will be ch.

First clears eofbit, then constructs a std::basic_istream::sentry object with noskipws set to true. Afterwards, if good()==false, calls setstate(failbit) and returns. Otherwise, if rdbuf() is not null, calls rdbuf()->sputbackc(ch), which calls rdbuf()->pbackfail(ch) if ch does not equal the most recently extracted character.

If rdbuf() is null or if rdbuf->sputbackc(ch) returns Traits::eof(), calls setstate(badbit).

In any case, sets the gcount() counter to zero.

Contents

[edit] Parameters

(none)

[edit] Return value

*this

[edit] Example

demonstrates the difference between modifying and non-modifying putback()

#include <sstream>
#include <iostream>
int main()
{
    std::stringstream s1("Hello, world"); // IO stream
    s1.get();
    if(s1.putback('Y')) // modifies the buffer
        std::cout << s1.rdbuf() << '\n';
    else
        std::cout << "putback failed\n";
 
    std::istringstream s2("Hello, world"); // input-only stream
    s2.get();
    if(s2.putback('Y')) // cannot modify input-only buffer
        std::cout << s2.rdbuf() << '\n';
    else
        std::cout << "putback failed\n";
 
    s2.clear();
    if(s2.putback('H')) // non-modifying putback
        std::cout << s2.rdbuf() << '\n';
    else
        std::cout << "putback failed\n";
}

Output:

Yello, world
putback failed
Hello, world

[edit] See also

unextracts a character
(public member function) [edit]
reads the next character without extracting it
(public member function) [edit]