public member function
<streambuf> <iostream>

std::basic_streambuf::sputbackc

int_type sputbackc (char_type c);
Put character back
Attempts to move the current position indicator of the controlled input sequence back to the character that precedes the current one.

Member function sungetc behaves in a similar way, but without taking any arguments.

Internally, the function calls the virtual protected member pbackfail if either there are no putback positions available at the get pointer (gptr), or if c does not match the character right before the current get position. Otherwise, the function uses the get pointer (gptr) directly, without calling virtual member functions.

Its behavior is the same as if implemented as:
1
2
3
4
5
6
int_type sputbackc(char_type c) {
  if ( (!gptr()) || (gptr()==eback()) || (!traits_type::eq(c,gptr()[-1])) )
    return pbackfail (traits_type::to_int_type(c));
  gbump(-1);
  return traits_type::to_int_type(*gptr());
}

Parameters

c
Character to be put back.
If this does not match the character at the put back position, the behavior depends on the pbackfail: it may either fail, be ignored, or override the character at that position.
Member type char_type is the type of the characters in the stream buffer (the first class template parameter).

Return Value

The value of the character put back, converted to a value of type int_type using member traits_type::to_int_type.
The function returns the end-of-file value (traits_type::eof()) on failure.
Member type int_type is an integral type able to represent any character value or the special end-of-file value.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// sputbackc example
#include <iostream>     // std::cin, std::cout, std::streambuf, std::streamsize

int main () {
  char ch;
  std::streambuf * pbuf = std::cin.rdbuf();

  std::cout << "Please, enter some letters and then a number: ";
  do {
    ch = pbuf->sbumpc();

    if ( (ch>='0') && (ch <='9') )
    {
      pbuf->sputbackc (ch);
      long n;
      std::cin >> n;
      std::cout << "You entered number " << n << '\n';
      break;
    }
  } while ( ch != std::streambuf::traits_type::eof() );

  return 0;
}

This example gets characters form the standard input one by one. When the first numeric digit is found, sputback is called to restore the position in the stream to that digit in order to be extracted as part of a number using the extraction operator >>.

Data races

Modifies the stream buffer object.
Concurrent access to the same stream buffer object may introduce data races.

Exception safety

Basic guarantee: if an exception is thrown, the stream buffer is in a valid state (this also applies to standard derived classes).

See also