1

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.

Loom
  • 9,768
  • 22
  • 60
  • 112
  • how are you able to read on ostringstream? Shouldn't this "std::ostringstream in;" be "std::istringstream in;" ? – Rush Nov 27 '14 at 15:54

2 Answers2

2

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
sehe
  • 374,641
  • 47
  • 450
  • 633
1

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

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252