c ++从ostream中获取一个字符串(序列化对象)

时间:2011-01-06 11:50:34

标签: c++ serialization stream

我有一个Image类,它具有以下实现

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

所以我可以通过调用

来序列化它
ostm << img; // which will write an string into the ostream.

是否可以从ostream中获取该字符串或将其直接序列化为字符串对象?

谢谢!

解决方案就像一个魅力。非常感谢你!

2 个答案:

答案 0 :(得分:1)

是的,您可以使用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();
}

答案 1 :(得分:0)

据推测,您的实际对象是iostreamstringstream。如果是iostream,您可以这样做:

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;

您需要istreambuf_iterator,因此需要像iostream这样的双向流。无论何时进行提取和插入,都应使用此方法,或使用stringstream(或fstream(如果使用文件)。

对于stringstream,只需使用其.str()成员函数将其缓冲区作为string获取。

相关问题