This question is asked quite often, so here is a way of doing it using stringstreams:
number to string
1 2 3 4 5 6 7 8 9 10
int Number = 123;//number to convert int a string
string Result;//string which will contain the result
stringstream convert; // stringstream used for the conversion
convert << Number;//add the value of Number to the characters in the stream
Result = convert.str();//set Result to the content of the stream
//Result now is equal to "123"
string to number
1 2 3 4 5 6 7 8
string Text = "456";//string containing the number
int Result;//number which will contain the result
stringstream convert(Text); // stringstream used for the conversion initialized with the contents of Textif ( !(convert >> Result) )//give the value to Result using the characters in the string
Result = 0;//if that fails set Result to 0
//Result now equal to 456
Simple functions to do these conversions
1 2 3 4 5 6 7
template <typename T>
string NumberToString ( T Number )
{
stringstream ss;
ss << Number;
return ss.str();
}
1 2 3 4 5 6 7
template <typename T>
T StringToNumber ( const string &Text )//Text not by const reference so that the function can be used with a
{ //character array as argument
stringstream ss(Text);
T result;
return ss >> result ? result : 0;
}
Looks good...but I have a question...does ss >> result filter out "junk" characters, i.e. if you put in "9kf84.85" into a double will it give you 984.85 or not do anything (giving you 0).
Also, 0 could theoretically be a valid value for what they are putting in...I would either ask them to specify a default value to return or throw an exception.
template <typename T>
T StringToNumber ( const string &Text, T defValue = T() )
{
stringstream ss;
for ( string::const_iterator i=Text.begin(); i!=Text.end(); ++i )
if ( isdigit(*i) || *i=='e' || *i=='-' || *i=='+' || *i=='.' )
ss << *i;
T result;
return ss >> result ? result : defValue;
}
leaves only numeric characters, sign and scientific notation (for doubles)
so that StringToNumber("3 ran 8 dom 9 chars 0.45e+3",0.0) will produce 3890450
The last version I provided leaves + and - in the string before converting it to a number (as a number can be in the form +123.456e-7), if you leave in the string other characters the result would be truncated
eg: "123/456" = 123
For the edits above: I've just noticed that I forgot to pass the string as reference