how can I convert istream * to string or just print it?

user1397417 picture user1397417 · Sep 5, 2013 · Viewed 13k times · Source

The below function part of connector/C++, it returns a istream*. if i just try and print it, it shows hex or a memory location because its a * type.

istream *stream = res->getBlob(1);

I tried to read & print it with this:

    string s; 
    while (getline(*stream, s))
    cout << s << endl; 

But this crashes with access violation though. any other way i can print it or convert to string?

the value of stream before the getline:

  • stream 0x005f3e88 {_Chcount=26806164129143632 } std::basic_istream > *

so it seems that its valid to me. I think it would be null or 0 if it failed

Answer

Dietmar K&#252;hl picture Dietmar Kühl · Sep 5, 2013

You can extract and print a std::istream by using its stream buffer:

std::cout << in->rdbuf();

Of course, this will consume the input and you may not be able to get it again. If you want to keep the content, you could write it an std::ostringstream instead and print the content using the str() method. Alternatively, you can directly construct a std::string from a stream, too, e.g.:

std::string content{ std::istreambuf_iterator<char>(*in),
                     std::istreambuf_iterator<char>() };

BTW, when you printed your stream pointer, you actually used the output operator for void const*: it prints the address the pointer is referring to. In C++03 you could even restore a correspondingly printed pointer by reading a void* using an std::istream: as long as the pointed to object wasn't deleted, you could get a pointer back that way! In C++11 pointer hiding is prohibited, however, to support optional garbage collection which may or may not be added to the language in the future. The guarantee about non-hidden pointers also helps member debuggers, though.