### Converting numbers to strings and strings to numbers

This question is asked quite often, so here is a way of doing it using stringstreams:

number to string
 ``12345678910`` ``````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
 ``12345678`` ``````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 Text if ( !(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
 ``1234567`` ``````template string NumberToString ( T Number ) { stringstream ss; ss << Number; return ss.str(); }``````

 ``1234567`` ``````template 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; }``````

Other ways:
Boost
http://www.boost.org/doc/libs/1_38_0/libs/conversion/lexical_cast.htm
C library
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf.html
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi.html
http://www.cplusplus.com/reference/clibrary/cstdlib/atol.html
http://www.cplusplus.com/reference/clibrary/cstdlib/atof.html
http://www.cplusplus.com/reference/clibrary/cstdlib/strtol.html
http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul.html
http://www.cplusplus.com/reference/clibrary/cstdlib/strtod.html

( I explain better with code examples than with words )
Last edited on
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.
 does `ss >> result` filter out "junk" characters
no, it stops at the 1st invalid character:
`"9kf84.85"` becomes 9

 Also, 0 could theoretically be a valid value for what they are putting in...
Notice that "simple" is underlined, those are just examples
A better string to number function:
 ``12345678910`` ``````template 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
Last edited on
And how would a function that returns a default value if any text except for mathimatical operators are found look like?
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
Last edited on
int result;
string text("123");
stringstream convert(text);

if(!(convert >> text))
result = 0;

cout << result;

why my answer is 3688360, when the text is "123" or "456"
Last edited on
 ``12`` ``````if(!(convert >> text)) result = 0;``````
You are getting the number back in the string, fix it in this way:
 ``12`` ``````if(!(convert >> result)) result = 0;``````
Well, I've been using these, which've worked quite well, for me:
 ``12345678910111213141516`` ``````template long atoi(const std::basic_string &str){ std::basic_stringstream stream(str); long res; return !(stream >>res)?0:res; } template std::basic_string itoa(long n,unsigned w=0){ std::basic_stringstream stream; if (w){ stream.fill('0'); stream.width(w); } stream <
Bazzy,
thank you!
 ``123456789101112`` `````` for (int i= 65; i<=90;i++ ) { convert << i; //error C2065: 'convert' : undeclared identifier drive_ID = convert.str(); //error C2065: 'convert' : undeclared identifier drive_ID = i + ":\\" ; // error C2228: left of '.str' must have class/struct/union drive_type = GetDriveType(drive_ID); if (drive_type != 3) continue; filename = drive_ID + ":\\Program Files\\JuniorT\\254.txt" ; exist = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); CloseHandle(exist);``````

i encount compile error of it
how to solve it?
Last edited on
You need to declare 'convert' before using it
 ``123456789101112131415161718192021222324252627282930313233343536373839`` ``````#include "stdafx.h" #include #include #include #include #include #include #include #include #include #include #include #include #include string drive_ID ; for (int i= 65; i<=90;i++ ) { stringstream convert; convert << i; //*error C2079: 'convert' uses undefined class 'std::basic_stringstream<_Elem,_Traits,_Alloc>' 1> with 1> [ 1> _Elem=char, 1> _Traits=std::char_traits, 1> _Alloc=std::allocator 1> ] warning C4552: '<<' : operator has no effect; expected operator with side-effect */ drive_ID = convert.str(); //error C2228: left of '.str' must have class/struct/union drive_ID = i + ":\\" ; drive_type = GetDriveType(drive_ID); if (drive_type != 3) continue; filename = drive_ID + ":\\Program Files\\JuniorT\\254.txt" ; exist = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); CloseHandle(exist);``````

still have error
how to amend~
thanks
Last edited on
Did you #include<sstream> ?
And need std::stringstream too
Bazzy +1
may i ask how to convert number 324545678 to wstring ?
try with wstringstream:
 ``123`` ``````wstringstream wss; wss << 324545678; wstring ws = wss.str();``````
Last edited on
Topic archived. No new replies allowed.