20

If I have an std::ostringstream object called oss, I understand I can do std::cout << oss.str() to print out the string. But doing oss.str() would result in the returned string being copied. Is there a way to print directly the underlying streambuf?

Thanks in advance!

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
Winston Huang
  • 201
  • 1
  • 2
  • 3

1 Answers1

25

Not if you're using std::ostringstream. The underlying buffer for this cannot be read from (hence the o in ostringstream), so you have to rely on the implementation to do it for you, via str().

However, if you use std::stringstream (note the lack of o), then the underlying buffer is readable, and basic_ostream's have a special overload forreading from buffers:

#include <iostream>
#include <sstream>

int main()
{
    std::stringstream ss1;
    ss1 << "some " << 111605 << " stuff" << std::flush;

    std::cout << ss1.rdbuf() << std::endl;
    std::cout << ss1.str() << std::endl;
}

Output:

some 111605 stuff
some 111605 stuff

(Example derived from here.)

This copies directly from the underlying buffer, without an intermediate copy.

Community
  • 1
  • 1
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • Thanks! Your solution works. I also found this post http://stackoverflow.com/questions/10009809/query-stdostringstream-content/10010160#10010160 where ostream is used to achieve the same thing. I was just wondering what's the difference between using ostream and stringstream. which one is more performant? – Winston Huang Mar 26 '13 at 14:13
  • @WinstonHuang: You have to profile it to find out which is more performant. I doubt it's any faster though, and it's certainly more complicated than just using `std::stringstream`. – GManNickG Mar 26 '13 at 15:29
  • Tried on gcc 9.1.0. `std::cout << ss1.str()` is faster anyway. (stdout was redirected to _/dev/null_). – anton_rh Oct 23 '20 at 15:30
  • https://coliru.stacked-crooked.com/a/d4ffa641487aa4cf – anton_rh Oct 23 '20 at 15:37