TITLE: text conversions with ostrstream and stringstream PROBLEM: meyer@offis.uni-oldenburg.de (Jochen Meyer) After four years of using (s)printf/(s)scanf in C++-programs I finally decided to convert to real C++ using the stream libraries. Certainly, the basics are quite logical and I certainly see the advantages of the stream concept. Yet I came across a problem which is fairly typical for the kind of problem with the standard classes and had cost me a couple of evenings: To convert a int to string I used a construct like: ostrstream s; int the_int = 3; string the_string; s << the_int; the_string = s.str(); Unfortunately, as I now understand it, this is not correct: ostrstream.str(void) _freezes_ the result char array, that means that it is no longer free'd upon destruction of s. Is my understanding right in this point? [ We actually use a function similar to the following (original code from Jamshid Afshar): template CString ToStr (const T& t) { ostrstream os; os << t << ends; // You should check os.good() here CString r (os.str()); os.rdbuf()->freeze(0); return r; } - adc ] RESPONSE: clamage@Eng.Sun.COM (Steve Clamage), 23 Feb 96 Correct. You can fix the problem by unfreezing the strstream, assuming that the string constructor makes a copy of the characters and does not store a pointer to them. s << the_int; string the_string(s.str()); // create and initialize string in one step s.rdbuf()->freeze(0); // unfreeze the ostrstream Notice that using strstreams introduces no new problems compared to using sprintf/sscanf and char arrays. Either way you have some concerns about buffer size and/or lifetime. The strstream classes actually ease some problems. You can write past the end of a buffer with sprintf, but you cannot do so with an ostrstream. The stream knows how big its buffer is (if it is a fixed buffer) and won't write past the end. You can also ask the stream if output to it was successful. There is no question that strstreams are kind of clunky, and are somewhat error-prone. At the time the iostream library was designed (1988-89) it was about the best that could be done. The new iostream library in the draft standard deprecates the strstream classes, and substitues a set of stringstream classes. The stringstream classes use a string object as a buffer instead of a char array. Memory allocation/deallocation is completely automatic and you never have to worry about when or whether to unfreeze or delete a buffer.