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
September 2, 2008 at 1:00 pm
[...] Click to see how to convert string to number Possibly related posts: (automatically generated)How to avoid unwanted stepping in debugging with visual studio [...]
September 3, 2008 at 9:31 am
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
October 1, 2008 at 4:45 am
grat!!thansk soo much
March 4, 2009 at 3:14 pm
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.
April 15, 2009 at 8:22 pm
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!
September 8, 2009 at 2:50 am
ur code are very useful~~thx!!!