Convert std::ostream to std::string

15,569

Solution 1

  • 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.

Solution 2

Try this

 std::ostringstream stream;
 stream << "Some Text";
 std::string str =  stream.str();
Share:
15,569
Danny
Author by

Danny

Updated on June 04, 2022

Comments

  • Danny
    Danny almost 2 years

    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)

  • M.M
    M.M about 7 years
    I don't think this works; the post you link to refers to an input stream's rdbuf.
  • jpo38
    jpo38 about 7 years
    @M.M: Just tested that (see live demo added to my post), it works when ostream is actually a stringstream, so I d'ont see why it would not work with others (like ofstream).
  • M.M
    M.M about 7 years
    stringstreams always hold the content in memory, whereas ofstreams don't, I'd expect they clear their buffer once written the current line or whatever
  • jpo38
    jpo38 about 7 years
    By the way, OP says I've found examples of converting std::ostringstream to std::string, so he knows that...
  • jpo38
    jpo38 about 7 years
    @M.M: You are probably right, I commented my post to mention that. Maybe the answer won't work when ostream is not actually a ostringstream...