C++ streambuf::sungetc() function
The C++ std::streambuf::sungetc() function is used to return the next character from the input sequence without advancing the current position of the stream buffer.
If no character is available, it returns EOF(end-of-file).
Syntax
Following is the syntax for std::streambuf::sungetc() function.
int_type sungetc();
Parameters
It does not accept any parameter.
Return Value
It returns the value of the new current character of the controlled input sequence, as a value of type int.
Exceptions
If an exception is thrown, the stream buffer is in a valid state.
Data races
It modifies the stream buffer object.
Example 1
In the following example, we are going to consider the basic usage of the sungetc() function.
#include <iostream>
#include <sstream>
int main() {
std::istringstream a("Car");
char b;
b = a.get();
a.rdbuf() -> sungetc();
b = a.get();
std::cout << "Result : " << b << std::endl;
return 0;
}
Output
Output of the above code is as follows −
Result : C
Example 2
Consider the following example, where we are going to use the sungetc() function followed by the sgetc() function.
#include <iostream>
#include <sstream>
int main() {
std::string x = "TP";
std::stringbuf y(x);
char x1 = y.sbumpc();
std::cout << "Read character: " << x1 << std::endl;
y.sungetc();
char x2 = y.sgetc();
std::cout << "After sungetc(), peeked character: " << x2 << std::endl;
return 0;
}
Output
Following is the output of the above code −
Read character: T After sungetc(), peeked character: T