std::string 和 int之间的相互转换

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

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 
string NumberToString ( T Number )
{
	stringstream ss;
	ss << Number;
	return ss.str();
}

1
2
3
4
5
6
7
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;
}


原文地址:
http://www.cplusplus.com/forum/articles/9645/

也可以参考这个:
http://stackoverflow.com/questions/191757/c-concatenate-string-and-int

你可能感兴趣的:(C/C++)