Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: what benefits do string streams offer?

could any one tell me about some practical examples on using string streams in c++, i.e. inputing and outputing to a string stream using stream insertion and stream extraction operators?

like image 357
Alan_AI Avatar asked Feb 25 '10 14:02

Alan_AI


2 Answers

You can use string streams to convert anything that implements operator << to a string:

#include <sstream>

template<typename T>
std::string toString(const T& t)
{
  std::ostringstream stream;
  stream << t;

  return stream.str();
}

or even

template <typename U, typename T>
U convert(const T& t)
{
  std::stringstream stream;
  stream << t;

  U u;
  stream >> u;

  return u;
}
like image 178
Gregory Pakosz Avatar answered Sep 20 '22 13:09

Gregory Pakosz


I use them mostly as memory buffers, in creating messages:

if(someVector.size() > MAX_SIZE)
{
    ostringstream buffer;
    buffer << "Vector should not have " << someVector.size() << " eleements";
    throw std::runtime_error(buffer.str());
}

or to construct complex strings:

std::string MyObject::GenerateDumpPath()
{
    using namespace std;

    std::ostringstream      dumpPath;

    // add the file name
    dumpPath << "\\myobject."
        << setw(3) << setfill('0') << uniqueFileId
        << "." << boost::lexical_cast<std::string>(state)
        << "_" << ymd.year 
        << "." << setw(2) << setfill('0') << ymd.month.as_number()
        << "." << ymd.day.as_number()
        << "_" << time.hours() 
        << "." << time.minutes() 
        << "." << time.seconds()
        << ".xml";

    return dumpPath.str();
}

It is useful because it brings all the extensibility of std::streams to using character buffers (ostreams extensibility and locales support, buffer memory management is hidden and so on).

Another example I've seen was the error reporting in gsoap library, using dependency injection: soap_stream_fault takes an ostream& parameter to report error messages in.

If you want you can pass it std::cerr, std::cout or an std::ostringstream implementation (I use it with a std::ostringstream implementation).

like image 32
utnapistim Avatar answered Sep 19 '22 13:09

utnapistim