Implementing toString() and fromString() using std::stringstream

Posted on: 16/08/2009

The classes istringstream & ostringstream can be utilized to create generic, templated, toString() & fromString() functions. This functionality (which is built-in in many languages, such as Java) may come in very handy, quite often.

Here’s a proposed implementation for such a request:

#include <iostream>
#include <string>
#include <sstream>

template <typename T>
std::string toString (const T &t) {
    std::ostringstream os;
    os << t;
    return os.str();

template <typename T>
T fromString (const std::string &str) {
    std::istringstream is(str);
    T t;
    is >> t;
    return t;

int main () {
    std::string three("3");
    int two=2;

    std::cout << fromString<int>(three) << std::endl;
    std::cout << toString(two) << std::endl;

It is important to note that the type T has some constraints:

  • In toString(): there must be an operator overloading of the form operator<<(ostream&, const T&).
  • In fromString(): there must be an operator overloading of the form operator>>(istream&, const T&), a default constructor for T, and a copy constructor for it.

Other than that, the technique is very useful.

Tip: boost::lexical_cast is also worth checking out (link) as it basically offers the same functionality, with some extra error checking.


1 Response to "Implementing toString() and fromString() using std::stringstream"

Already seen on developpez.com 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 27 other followers


%d bloggers like this: