简体   繁体   中英

Convert std::ostream to std::string

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 aa 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 MM, 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.

Try this

 std::ostringstream stream;
 stream << "Some Text";
 std::string str =  stream.str();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM