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


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

也可以参考这个:
http://stackoverflow.com/questions/191757/c-concatenate-string-and-int
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值