The C++ std::istream::unget() function is used to put back the last character extracted from an input stream, moving the streams internal position indicator one character back. This allows the character to be read again in subsequent input operations.
SyntaxFollowing is the syntax for std::istream::unget() function.
istream& unget();Parameters
It does not accept any parameter.
Return ValueThis function returns the basic_istream object (*this).
ExceptionsIf an exception is thrown, the object is in a valid state.
Data racesModifies the stream object.
ExampleIn the following example, we are going to consider the basic usage of the unget() function.
#include <iostream> #include <sstream> int main() { std::istringstream x("Namaste"); char a; x.get(a); std::cout << "Read: " << a << std::endl; x.unget(); x.get(a); std::cout << "Read again: " << a << std::endl; return 0; }Output
Output of the above code is as follows −
Read: N Read again: NExample
Consider the following example, where we are going to use the unget() function after multiple reads.
#include <iostream> #include <sstream> int main() { std::istringstream a("TutorialsPoint"); char x; a.get(x); std::cout << "First Read: " << x << std::endl; a.get(x); std::cout << "Second Read: " << x << std::endl; a.unget(); a.get(x); std::cout << "Third Read: " << x << std::endl; return 0; }Output
Following is the output of the above code −
First Read: T Second Read: u Third Read: uExample
Let's look at the following example, where we are going to use the unget() function in a loop.
#include <iostream> #include <sstream> int main() { std::istringstream a("1123245"); char x; while (a.get(x)) { if (x == '4') { a.unget(); break; } std::cout << x << " "; } std::cout << std::endl; a.get(x); std::cout << "Character put back: " << x << std::endl; return 0; }Output
If we run the above code it will generate the following output −
1 1 2 3 2 Character put back: 4
istream.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4