I think you misunderstood this concept. The line
cout.rdbuf(ss.rdbuf());
sets the pointer to the buffer. It redirects cout
to ss
and not to console. If you write into cout
it will be written to ss
.
I hope this clears it for you
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::streambuf *backup;
backup = std::cout.rdbuf();
std::stringstream ss;
std::cout.rdbuf(ss.rdbuf());
std::cout << "Test" << std::endl;
std::cout.rdbuf(backup);
std::cout << ss.rdbuf();
return 0;
}
In the example code I create a copy of the current pointer of cout
's buffer. Next I redirect the cout
to ss
. When I write into cout
it is written into ss
's buffer. Next I redirect cout
back to console and print the content of ss
.
If you want to manipulate the buffer you need somethink like
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
int main() {
std::stringstream ss{ "test" };
std::stringbuf *pbuf = ss.rdbuf();
char buffer[80];
pbuf->sgetn (buffer,80);
std::streambuf *pbuf2 = std::cout.rdbuf();
pbuf2->sputn (buffer, std::strlen(buffer));
return 0;
}