Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::ostream to std::string

Tags:

c++

std

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)

like image 456
Danny Avatar asked Mar 18 '17 07:03

Danny


2 Answers

  • 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

  • Finally, as commented by M.M, if your 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.
like image 141
jpo38 Avatar answered Oct 23 '22 05:10

jpo38


Try this

 std::ostringstream stream;
 stream << "Some Text";
 std::string str =  stream.str();
like image 1
Abi Avatar answered Oct 23 '22 06:10

Abi