public member function
<streambuf> <iostream>

std::basic_streambuf::sungetc

int_type sungetc();
Decrease current position
Attempts to move the current position indicator of the controlled input sequence back one position to the character that precedes the current one, making the character at that position available once again for the next input operation.

Internally, the function calls the virtual protected member pbackfail if the get pointer (gptr) points to the buffer beginning (eback) when the function is called. Otherwise, the function uses the get pointer (gptr) directly, without calling any virtual member functions.

Its behavior is the same as if implemented as:
1
2
3
4
5
int_type sungetc() {
  if ( (!gptr()) || (gptr()==eback()) ) return pbackfail();
  gbump(-1);
  return traits_type::to_int_type(*gptr());
}

Parameters

none

Return Value

The value of the new current character of the controlled input sequence, 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
// sungetc 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->sungetc ();
      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 standard input one by one. When the first numeric digit is found, sungetc 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