• Articles
• Converting numbers to strings and string
Apr 6, 2009 (last update: May 19, 2009)

# Converting numbers to strings and strings to numbers

Score: 3.0/5 (36 votes)
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.pickinpatchfarm.com/doc/libs/1_38_0/libs/conversion/lexical_cast.htm
C library
http://www.pickinpatchfarm.com/reference/clibrary/cstdio/sprintf.html
http://www.pickinpatchfarm.com/reference/clibrary/cstdlib/itoa.html
http://www.pickinpatchfarm.com/reference/clibrary/cstdlib/atoi.html
http://www.pickinpatchfarm.com/reference/clibrary/cstdlib/atol.html
http://www.pickinpatchfarm.com/reference/clibrary/cstdlib/atof.html
http://www.pickinpatchfarm.com/reference/clibrary/cstdlib/strtol.html
http://www.pickinpatchfarm.com/reference/clibrary/cstdlib/strtoul.html
http://www.pickinpatchfarm.com/reference/clibrary/cstdlib/strtod.html

( I explain better with code examples than with words )

### C++

• 1793521592 2018-02-23
• 2864591591 2018-02-23
• 6167231590 2018-02-23
• 3669201589 2018-02-23
• 7946381588 2018-02-23
• 8957701587 2018-02-23
• 3891941586 2018-02-23
• 6039851585 2018-02-23
• 2573991584 2018-02-23
• 7728781583 2018-02-23
• 3731582 2018-02-23
• 1007451581 2018-02-22
• 8908121580 2018-02-22
• 141161579 2018-02-22
• 9421578 2018-02-22
• 2826901577 2018-02-22
• 3647361576 2018-02-22
• 5717551575 2018-02-22
• 523811574 2018-02-22
• 6439871573 2018-02-22