Libstdc++-v3 provides the new
i/ostringstream-classes, (<sstream>), but for compatibility
with older implementations you still have to use
i/ostrstream (<strstream>):
#ifdef HAVE_SSTREAM
#include <sstream>
#else
#include <strstream>
#endif
strstream is considered to be
deprecated
strstream is limited to
char with ostringstream you don't
have to take care of terminating the string or freeing its
memory
istringstream can be re-filled
(clear(); str(input);)
You can then use output-stringstreams like this:
#ifdef HAVE_SSTREAM
std::ostringstream oss;
#else
std::ostrstream oss;
#endif
oss << "Name=" << m_name << ", number=" << m_number << std::endl;
...
#ifndef HAVE_SSTREAM
oss << std::ends; // terminate the char*-string
#endif
// str() returns char* for ostrstream and a string for ostringstream
// this also causes ostrstream to think that the buffer's memory
// is yours
m_label.set_text(oss.str());
#ifndef HAVE_SSTREAM
// let the ostrstream take care of freeing the memory
oss.freeze(false);
#endif
Input-stringstreams can be used similarly:
std::string input;
...
#ifdef HAVE_SSTREAM
std::istringstream iss(input);
#else
std::istrstream iss(input.c_str());
#endif
int i;
iss >> i;
One (the only?) restriction is that an istrstream cannot be re-filled:
std::istringstream iss(numerator);
iss >> m_num;
// this is not possible with istrstream
iss.clear();
iss.str(denominator);
iss >> m_den;
If you don't care about speed, you can put these conversions in
a template-function:
template <class X>
void fromString(const string& input, X& any)
{
#ifdef HAVE_SSTREAM
std::istringstream iss(input);
#else
std::istrstream iss(input.c_str());
#endif
X temp;
iss >> temp;
if (iss.fail())
throw runtime_error(..)
any = temp;
}
Another example of using stringstreams is in this howto.
I have read the Josuttis book on Standard C++, so some information
comes from there. Additionally, there is information in
"info iostream", which covers the old implementation that gcc 2.95.x
uses.
