Redirect from a std::ostringstream to another std::ostringstream

488 views Asked by At

I need write data from some std::ostringstream to another std::ostringstream. Of course, I can use str() function

std::ostringstream in;
std::ostringstream out;

in << "just a test"; // it's just an example. I mean that stream in is filled somewhere
...
out << in.str();

I'd like to know if there is more direct way to do the same.

2

There are 2 answers

0
sehe On BEST ANSWER

You can reassign the associated buffers:

os2.rdbuf(os1.rdbuf());

That effectively aliases the ostream.

In fact, you can even construct ostream directly from a streambuffer pointer IIRC


Similarly, you can append the whole buffer to another stream without reassigning:

std::cout << mystringstream.rdbuf(); // prints the stringstream to console
0
vsoftco On

The copy assignment operator/copy constructor are deleted. However, you can use the member function swap (C++11), or std::swap, to swap the content. Or, you can use the move assignment operator (C++11) to move one into the other. This solution works only in the case when you don't care about the content of the source stringstream.

Example:

out = std::move(in); // C++11
out.swap(in); // C++11
std::swap(out, in); 

PS: I just realized that g++ does not compile any of the above lines (it seems it doesn't support move/swap for ostringstream), however, clang++ compiles it. According to the standard (27.8.4), swap/move should work. See C++ compiler does not recognize std::stringstream::swap