Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write ostringstream directly to cout

Tags:

c++

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!

like image 885
Winston Huang Avatar asked Mar 26 '13 05:03

Winston Huang


1 Answers

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.

like image 87
GManNickG Avatar answered Nov 15 '22 15:11

GManNickG