Re: STL equiv of Java ByteArrayOutputStream by tom_usenet
tom_usenet
Fri Nov 21 04:28:16 CST 2003
On Fri, 21 Nov 2003 01:50:11 GMT, "Dave Rathnow" <drathnow@yahoo.com>
wrote:
>Hi,
>
>I've been under the Java umbrella for the past few years and have recently
>moved back to C++. I'm trying to remember how all the C++ stream
>objects work and would like to find one that works similar to Java's
>ByteArrayOutputStream. I need to serialize some data to (and from) a byte
>stream for tranmission over a com link. I'm sure it's out there but I can't
>find it.
>
>Could someone tell me which animal out of the stream zoo I could use?
Two options. If you already have a char buffer ready to write to, then
strstream is the bunny from <strstream>:
ostrstream oss(mycharbuffer, size);
oss << "Stuff to transmit";
//oss will hit EOF if buffer is filled.
//now send mycharbuffer (note it isn't null-terminated, but you
//probably don't want that anyway)
There are a few gotchas with strstreams, but the above usage is
generally the hardest to get wrong.
Alternatively, you have the string based version from <sstream>:
ostringstream oss;
oss << "Stuff to transmit";
std::string s = oss.str();
//send s, using s.data().
Personally I tend to find ostrstream better suited to this kind of
work, but unfortunately the C++ standard's committee (in its wisdom)
has chosen to deprecate strstream. I wouldn't be too concerned about
this though.
Tom