Winston Huang
Winston Huang

Reputation: 201

how to write ostringstream directly to cout

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!

Upvotes: 20

Views: 18516

Answers (1)

GManNickG
GManNickG

Reputation: 503855

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.

Upvotes: 26

Related Questions