How to Convert string to Number

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

6 Responses to “How to Convert string to Number”

  1. How To Convert a Number To std::string « My Experiments with C++ Says:

    [...] Click to see how to convert string to number Possibly related posts: (automatically generated)How to avoid unwanted stepping in debugging with visual studio [...]

  2. Ahsan Says:

    std::stringstream is definitely better over sprintf.

    There is still a more better approach using the boost conversion library.

    You can also use boost::lexical_cast for the same purpose.

    #include

    std::string value = “123.456″;
    float f = boost::lexical_cast(value);

    The additional benefit is that when you use stringstream to convert an incorrect number (e.g if the string is “abc.def” and you try to convert it to number), you will get a wrong result.

    boost::lexical_cast throws a boost::bad_lexical_cast exception when the conversion may not succeed.

    http://www.boost.org/doc/libs/1_36_0/libs/conversion/lexical_cast.htm

  3. great Says:

    grat!!thansk soo much

  4. Nibu Thomas Says:

    stringstream is a heavy class to be used just for number conversion. A simple sizeof(strinstream) gives 140 bytes. Also it’s a buffered stream which is too much for a simple number conversion. :) Well this IMO. ;)

  5. How to Get Six Pack Fast Says:

    If you want to hear a reader’s feedback :) , I rate this post for four from five. Detailed info, but I just have to go to that damn yahoo to find the missed bits. Thank you, anyway!

  6. eden88 Says:

    ur code are very useful~~thx!!!

Leave a Reply