Convert to STL String

January 10, 2005

How to use ostringstream to take advantage of conversion to a std::string. This will convert any base type or any other type that has an ostream overload to a std::string.

#include <string>
#include <sstream>
template <typename T>
std::string tostr(const T& x)
	std::ostringstream o;
   	o << x;
	return o.str();

To check for an error condition on the conversion, simply do an if test on o << x;

Related Posts

1 Comment

Comment February 17, 2005 by
nice method! and nice site! greetings from frankfurt germany...