The basic_istream::unget function is used to unget the character, which also decreases the location by a single character and allows the retrieved character to be reused. The appropriate header file should be provided.
The objective of using the basic_istream::unget method is to return a character to the stream, allowing it to be easily processed at a later stage. This function can lower the location by one character, essentially restoring the previously removed character.
Header File
It included the <iostream> header file.
Syntax:
It has the following syntax:
basic_istream& unget();
Parameters: The basic_istream::unget function takes no parameters.
Return value: The basicistream object is returned by the method basicistream::unget.
The following programs explain std::basic_istream::unget:
Example:
Filename: Ungetting1.cpp
// Program to implement the use of basic_istream::unget()
#include <bits/stdc++.h>
using namespace std;
// main
int main()
{
// decreasing the size of the string stream
istringstream con("ProgrammingLanguage");
char a = con.get();
if (con.unget()) {
char be = con.get();
cout << "We got: " << a << endl;
cout << "After the ungetting, the character is: "
<< be << endl;
}
return 0;
}
Output:
We got: P
After the ungetting, the character is: P
Example 2:
Filename: Ungetting2.cpp
// Program to implement the use of basic_istream::unget()
#include <bits/stdc++.h>
using namespace std;
// main
int main()
{
// decreasing the size of the string stream
istringstream con("Language");
char a = con.get();
if (con.unget()) {
char be = con.get();
cout << "We got: " << a << endl;
cout << "After the ungetting, the character is: "
<< be << endl;
}
return 0;
}
Output:
We got: L
After the ungetting, the character is: L
Explanation:
- istringstream con("Language");: It initializes an input string stream con using the string "Language".
- char a= con.get;: If (con. unget) is true, it reads the first letter from the stream ('L') and puts it in variable a. { ... }: Moves to "unget" the character from the stream. The unget method returns the stream location of one character. If successful, it provides true.
Within the if block:
- char be = con.get;: After unget, reads an element from the stream. It should return the same element that was previously read ('L') because it was "unget" back to the stream.
- The values of a and be are printed on the terminal.