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
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 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
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;
}


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:
1
2
3
4
5
6
7
8
9
10
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
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
Your error is here:
1
2
if(!(convert >> text))
result = 0;
You are getting the number back in the string, fix it in this way:
1
2
if(!(convert >> result))
result = 0;
Well, I've been using these, which've worked quite well, for me:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename T>
long atoi(const std::basic_string<T> &str){
	std::basic_stringstream<T> stream(str);
	long res;
	return !(stream >>res)?0:res;
}
template <typename T>
std::basic_string<T> itoa(long n,unsigned w=0){
	std::basic_stringstream<T> stream;
	if (w){
		stream.fill('0');
		stream.width(w);
	}
	stream <<n;
	return stream.str();
}
Bazzy,
thank you!
1
2
3
4
5
6
7
8
9
10
11
12
 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include "stdafx.h"
#include <windows.h>
#include <math.h>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <string.h>

#include <WINERROR.H>
#include <stddef.h>
#include <stdlib.h>
#include <wchar.h>
#include <tchar.h>

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<char>,
1>            _Alloc=std::allocator<char>
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);


after adding stringstream convert;

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:
1
2
3
wstringstream wss;
wss << 324545678;
wstring ws = wss.str();
Last edited on
Topic archived. No new replies allowed.