• 文章
  • 數字轉換為字串,字串轉換為數字
釋出
2009年4月6日 (最後更新:2009年5月19日)

數字轉換為字串,字串轉換為數字

評分:3.3/5 (48 票)
*****
這個問題經常被問到,所以這裡提供一種方法,使用stringstreams:

數字轉字串
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 <b>Number</b> to the characters in the stream

Result = convert.str();//set <b>Result</b> to the content of the stream

//<b>Result</b> now is equal to <b>"123"</b> 


字串轉數字
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 <b>Text</b>

if ( !(convert >> Result) )//give the value to <b>Result</b> using the characters in the string
    Result = 0;//if that fails set <b>Result</b> to <b>0</b>
//<b>Result</b> now equal to <b>456</b> 


簡單的函式來實現這些轉換
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 )//<b>Text</b> 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;
}


其他方法
Boost
http://www.boost.org/doc/libs/1_38_0/libs/conversion/lexical_cast.htm
C 庫
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


(我更喜歡用程式碼示例來解釋,而不是用文字)