How to Convert string to Number

September 2, 2008

String streams are of great help for conversion between strings and numbers. The folowing code snippet converts string to int.

string MyString("123");
stringstream SStream(MyString);
int Num = 0;
SStream >> Num;

The resulting Num contains the value 123.

It can be extended for any number type (float, double etc.) So the conversion function can be enhanced as a template as given below.

#include <iostream>
#include <sstream>
using namespace std;
template<typename T>

T Convert(const string& MyString)
{
   stringstream SStream(MyString);
   T Num = 0;
   SStream >> Num;
   return Num;
}

int main()
{
   string Str("123.45");
   float fNum = Convert<float>(Str);
   Str = "24";
   int iNo = Convert<int>(Str);
   return 0;
}


Click here to see how to convert a number to string


Click here to see how to convert CString to std::string