basic_streambuf::sputbackc

To put a character back into the stream.

int_type sputbackc(char_type c);

Remarks

The function sputbackc() will replace a character extracted from the stream with another character. The results are not assured if the putback is not immediately done or a different character is used.

If successful, returns a pointer to the get pointer as an int_type otherwise returns pbackfail(c).

#include <iostream> #include <sstream> std::string buffer = "ABCDEF"; int main() { using namespace std; stringbuf strbuf(buffer); char ch; ch = strbuf.sgetc(); // extract first character cout << ch; // show it //get the next character ch = strbuf.snextc(); // if second char is B replace first char with x if(ch =='B') strbuf.sputbackc('x'); // read the first character now x cout << (char)strbuf.sgetc(); strbuf.sbumpc(); // increment get pointer // read second character cout << (char)strbuf.sgetc(); strbuf.sbumpc(); // increment get pointer // read third character cout << (char)strbuf.sgetc(); // show the new stream after alteration strbuf.pubseekoff(0, ios::beg); cout << endl; cout << (char)strbuf.sgetc(); while( (ch = strbuf.snextc()) != EOF) cout << ch; return 0; }

Result:

AxBC

xBCDEF