Legacy code I maintain collects text into an std::ostream
. I'd like to convert this to a std::string
.
I've found examples of converting std::sstringstream
, std::ostringstream
etc to std::string
but not explicitly std::ostream
to std::string
.
How can I do that? (Ancient C++ 98 only, no boost please)
If you have a a stringstream
or a ostreamstring
, object or reference, just use the ostringstream::str()
method that does exactly what you want: extract a string
. But you know that and you apparently have a ostream
object, not a stringstream
nor a ostreamstring
.
If your ostream reference is actually a ostringstream
or a stringstream
, use ostream::rdbuf
to get a streambuf
, then use this post to see how to extract a string
.
Example:
#include <iostream>
#include <sstream>
std::string toString( std::ostream& str )
{
std::ostringstream ss;
ss << str.rdbuf();
return ss.str();
}
int main() {
std::stringstream str;
str << "Hello";
std::string converted = toString( str );
std::cout << converted;
return 0;
}
Live demo: http://cpp.sh/6z6c
ostream
is a ofstream
or an iostream
, most likely it clears its buffer so you may not be able to extract the full content as proposed above.Try this
std::ostringstream stream;
stream << "Some Text";
std::string str = stream.str();
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