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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With