开发者

c++ get an string(serialized object) from ostream

开发者 https://www.devze.com 2023-02-03 01:00 出处:网络
I have an Image class which has the following implementation friend std::ostream& operator << ( std::ostream &os,Image* &img);

I have an Image class which has the following implementation

friend std::ostream& operator << ( std::ostream &os,Image* &img);

So I can serialize it by calling

ostm << img; // which will write an string into the ostream.

Is it possible to get that string out 开发者_C百科of the ostream or serialize it directly into an string object?

Thanks!

The solutions worked like a charm. Thank you so much!


Yes, you can use a std::ostringstream.

E.g.

#include <sstream>
#include <string>
#include <stdexcept>

std::string Serialize( const Image& img )
{
    std::ostringstream oss;

    if (!(oss << img))
    {
        throw std::runtime_error("Failed to serialize image");
    }

    return oss.str();
}


Presumably your actual object is an iostream, or a stringstream. If an iostream, you can do this:

std::iostream ss;
ss << "Some text\nlol";
std::string all_of_it((std::istreambuf_iterator<char>(ss)), std::istreambuf_iterator<char>());
std::cout << all_of_it; // Outputs: "Some text", then "lol" on a new line;

You need the istreambuf_iterator, hence the requirement for a bidirectional stream like iostream. Whenever you have extraction as well as insertion, you should use this, or a stringstream (or an fstream if working with files).

For a stringstream, just use its .str() member function to obtain its buffer as a string.

0

精彩评论

暂无评论...
验证码 换一张
取 消