public member function
<streambuf> <iostream>

std::streambuf::sungetc

int 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 sungetc() {
  if ( (!gptr()) || (gptr()==eback()) ) return pbackfail();
  gbump(-1);
  return *gptr();
}

Return Value

The value of the new current character of the controlled input sequence, as a value of type int.
The function returns the end-of-file value (EOF) on failure.

Example

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

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 != 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