Programming Tips & Tricks

Home Categories: C# | C++ | General | Other

C++ Tips & Tricks: Format Conversions with StringStream

Converting between numbers and number-strings (e.g. 123 and "123" ) can be quite messy with old C functions like _itoa, atoi, atof etc.
Luckily the STL gives us a nice and clean way to convert between strings and numeric types with the std::stringstream class.
With the << operator, you can read any string or numeric value into a stringstream, and with the >> operator you can read the value into some variable, and stringstream takes care of the conversion from the input value to the type of the output variable.
Below is some self-explaining sample program with templated generic functions that convert between any kind of numeric value and std::string:

#include < sstream >
#include < iostream >

using namespace std;

template <class T>
T fromstring ( std::string s )
{
T result;
std::stringstream str;
str << s;
str >> result;
return result;
}

template <class T>
std::string tostring ( T d )
{
std::string s;
std::stringstream str;
str << d;
str >> s;
return s;
}

void main () 
{
string s = tostring<double> ( 123.456 );
double d = fromstring<double>("124.123");
std::cout << s << std::endl;
std::cout << d << std::endl;