basic_istream::putback() in C++ with Examples

The basic_istream::putback() used to put the character back in the input string. This function is present in the iostream header file. Below is the syntax for the same:

Header File:

#include<iostream>

Syntax:

basic_istream& putback (char_type ch);

Parameter:

  • ch: It represents the character to be put into the input string back.

Return Value: The iostream::basic_istream::putback() return the basic_istream object.



Below are the programs to understand the implementation of std::basic_istream::putback() in a better way:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code for basic_istream::putback()
#include <bits/stdc++.h>
  
using namespace std;
  
int main()
{
    stringstream gfg1("GeeksforGeeks");
    gfg1.get();
  
    // putback A into the input string
    if (gfg1.putback('A'))
        cout << gfg1.rdbuf() << endl;
  
    istringstream gfg2("GeeksforGeeks");
    gfg2.get();
  
    if (gfg2.putback('A'))
        cout << gfg2.rdbuf() << endl;
    else
        cout << "putback is failed here\n";
  
    gfg2.clear();
  
    // Again putback G in the string
    if (gfg2.putback('G'))
        cout << gfg2.rdbuf() << endl;
}

chevron_right


Output:

AeeksforGeeks
putback is failed here
GeeksforGeeks

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ code for basic_istream::putback()
#include <bits/stdc++.h>
  
using namespace std;
  
int main()
{
    stringstream gfg1("GOOD");
    gfg1.get();
  
    // putback B into the input string
    if (gfg1.putback('B'))
        cout << gfg1.rdbuf() << endl;
  
    istringstream gfg2("GOOD");
    gfg2.get();
  
    if (gfg2.putback('B'))
        cout << gfg2.rdbuf() << endl;
    else
        cout << "putback is failed here\n";
  
    gfg2.clear();
  
    // Again putback G in the string
    if (gfg2.putback('G'))
        cout << gfg2.rdbuf() << endl;
}

chevron_right


Output:

BOOD
putback is failed here
GOOD

Reference: http://www.cplusplus.com/reference/istream/istream/putback/

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.