Posted by: rmn 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:
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.
18/12/2009 at 23:47
Already seen on developpez.com