3
using namespace std;
string str{ "text" };
stringstream ss{ str };
cout.rdbuf(ss.rdbuf());
cout.flush(); //cout<<endl;

This code is expected to print text,but showing nothing.

I associate ss to stdout then flush it,but I don't know why it didn't work even if I refer to many illustration.

cout<<rdbuf(ss);

this is OK but where's the different? : (

Iman
  • 410
  • 7
  • 17
ZeBin Liu
  • 47
  • 3

2 Answers2

4

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;
}
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
2

As a complement to @Thomas Sablik answer, here is a code example for printing "text" by redirecting streams:

std::stringstream ss;
ss.basic_ios<char>::rdbuf(std::cout.rdbuf());
ss << "text";
std::cout.flush();

If you want to copy the content of ss's streambuf to std::cout, you can use inserter directly:

std::string str{ "text" };
std::stringstream ss{ str };
std::cout << ss.rdbuf();
std::cout.flush();

http://wordaligned.org/articles/cpp-streambufs

felix
  • 2,213
  • 7
  • 16