0

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 of the ostream or serialize it directly into an string object?

Thanks!

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

6
  • 1
    Do you really mean Image* &img ? For output a const Image& would be more conventional. Commented Jan 6, 2011 at 11:55
  • Yes, that is what the original code says. Commented Jan 6, 2011 at 12:34
  • Please post complete code; it's not possible to debug your operator<< without being able to see its implementation. Commented Jan 6, 2011 at 12:42
  • I thought you said the original code used const Image& as the second parameter to operator<<? The code you have posted looks very suspect. Typically an op<< shouldn't have to create or modify objects being output. What's the definition of Image, the constructor that you are using and cvSaveImage ? Commented Jan 6, 2011 at 13:45
  • I find it hard to believe that std::ostringstream would cause a memory error unless you're feeding it masses of data. Can you show the definition of Image? Commented Jan 6, 2011 at 14:37

2 Answers 2

1

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(); } 
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.