數字轉字符串:
用C++的streanstream:
#include <sstream>
#Include <string>
string num2str(double i)
{
stringstream ss;
ss<<i;
return ss.str();
}
#Include <string>
string num2str(double i)
{
stringstream ss;
ss<<i;
return ss.str();
}
字符串轉數字:
int str2num(string s)
{
int num;
stringstream ss(s);
ss>>num;
return num;
}
{
int num;
stringstream ss(s);
ss>>num;
return num;
}
上面方法很簡便, 缺點是處理大量數據轉換速度較慢..
C library中的sprintf, sscanf 相對更快
可以用sprintf函數將數字輸出到一個字符緩衝區中. 從而進行了轉換...
例如:
已知從0點開始的秒數(seconds) ,計算出字符串"H:M:S", 其中H是小時, M=分鐘,S=秒
int H, M, S;
string time_str;
H=seconds/3600;
M=(seconds%3600)/60;
S=(seconds%3600)%60;
char ctime[10];
sprintf(ctime, "%d:%d:%d", H, M, S); // 將整數轉換成字符串
time_str=ctime; // 結果
string time_str;
H=seconds/3600;
M=(seconds%3600)/60;
S=(seconds%3600)%60;
char ctime[10];
sprintf(ctime, "%d:%d:%d", H, M, S); // 將整數轉換成字符串
time_str=ctime; // 結果
與sprintf對應的是sscanf函數, 可以將字符串轉換成數字
char str[] = "15.455";
int i;
float fp;
sscanf( str, "%d", &i ); // 將字符串轉換成整數 i = 15
sscanf( str, "%f", &fp ); // 將字符串轉換成浮點數 fp = 15.455000
//打印
printf( "Integer: = %d ", i+1 );
printf( "Real: = %f ", fp+1 );
return 0;
int i;
float fp;
sscanf( str, "%d", &i ); // 將字符串轉換成整數 i = 15
sscanf( str, "%f", &fp ); // 將字符串轉換成浮點數 fp = 15.455000
//打印
printf( "Integer: = %d ", i+1 );
printf( "Real: = %f ", fp+1 );
return 0;
輸出如下:
Integer: = 16
Real: = 16.455000