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

August 16th, 2009 § 1 Comment

The classes istringstream and 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.

Tagged: , ,

§ One Response to Implementing toString() and fromString() using std::stringstream

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

What’s this?

You are currently reading Implementing toString() and fromString() using std::stringstream at 0x.

meta