HomeC&C++WainTutorialsSamplesTip & TrickTools


As variables in C++ has a type, one will frequently have to convert between types.
I will here show how to convert a int, double, etc. to a std::string, and from a std::string to a int, double, etc. First the easy part, to convert to a string:
template <typename T>
std::string ToString(T aValue)
{
   std::stringstream ss;
   ss << aValue;
   return ss.str();
}
You can then use it this way:
std::string s;
int i = 444;
s = ToString(i);
double d = 123.0/444.0;
s = ToString(d);
Now to convert from a string to a int, double, etc.:
template <typename T>
bool FromString(T &aValue, const std::string &aStr)
{
   std::stringstream ss(aStr);
   return ss >> aValue;
}
To use it:
std::string s = "123";
int i;
if(FromString(i, s))
{
   std::cout << "Success: " << i << std::endl;
}
else
{
   std::cout << "Failed!" << std::endl;
}
You will have to include: iostream, sstream and string