In C++, putback(c) pushes the character c back into an input stream. The next read gets c first, as if it had never been taken.
It is handy in small parsers: you read a character, find out it is not what you wanted, and give it back. Include <iostream> to use it.
This is a member function of std::istream. You call it with a dot on a stream object, for example std::cin, std::cout, a file stream, or a std::stringstream. A stream is simply C++'s way to read or write data one piece after another.
Syntax
Call putback on an input stream and pass the character to give back.
C++
char c;
in.get(c);
in.putback(c); // c will be read again
Call
What it does
in.putback(c)
Returns the character c to the stream.
in.get(c); in.putback(c);
The normal pair: read a character, then give it back.
if (!in.putback(c))
Tests whether the put back worked.
Only the character you just read is guaranteed to be accepted. Putting back a different character, or going back several steps, may fail.
Library declarations
C++
istream& putback(char_type ch);
Parameters
Parameter
Description
ch
Required. The character to put back. Use the character that was read last.
Return Value
Return Value
Description
istream&
A reference to the stream. If putting back was not possible, badbit or failbit is set, and the stream is false in a condition.
C++ Examples
Example 1 — Put Back a Character and Read It Again
Read a letter, give it back, and read it once more.
C++
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("AB");
char c = 0;
char again = 0;
in.get(c);
std::cout << "first read: " << c << '\n';
in.putback(c);
in.get(again);
std::cout << "after putback: " << again << '\n';
in.get(c);
std::cout << "next: " << c << '\n';
return 0;
}
Output
first read: A
after putback: A
next: B
How It Works
in.get(c) takes A from the stream. Only B is left.
in.putback(c) gives A back, so the stream holds AB again.
The next get() returns A once more. After that, the third read returns B.
Example 2 — Read a Number, Then Give Back the Operator
Read digits with get(). The first non-digit is put back so the next step can use it.
C++
#include <cctype>
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("42+7");
int number = 0;
char c = 0;
while (in.get(c)) {
if (!std::isdigit(c)) {
in.putback(c);
break;
}
number = number * 10 + (c - '0');
}
std::cout << "number: " << number << '\n';
std::cout << "operator: " << static_cast<char>(in.get()) << '\n';
return 0;
}
Output
number: 42
operator: +
How It Works
The loop reads 4 and 2, adds them to number, and then reads +.
+ is not a digit, so it is put back with putback(c) and the loop stops.
The next get() returns the + that was given back, so the program can handle the operator separately.
Example 3 — putback() at the Start of a Stream
There is nothing to go back to before the first character, so the call fails.