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.

1
  • how are you able to read on ostringstream? Shouldn't this "std::ostringstream in;" be "std::istringstream in;" ? Commented Nov 27, 2014 at 15:54

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.