C++ 中字串與數字的轉換
阿新 • • 發佈:2019-01-07
數字轉字串
1.sprintf_s函式
//sprintf函式
int a = 100;
float b = 10.30;
char str[10];
sprintf_s(str,"%d",a);
cout <<"a的字串型別:"<< str<<endl;
sprintf_s(str, "%.3lf", b);
cout << "b的字串型別:" << str << endl;
sprintf_s(str, "%x", a);
cout << "a的16進製表示:" << str << endl;
注:sprintf_s()是sprintf()的安全版本,通過指定緩衝區長度來避免sprintf()存在的溢位風險。
用於轉換的格式字元:
%c 單個字元
%d 十進位制整數(int)
%ld 十進位制整數(long)
%f 十進位制浮點數(float)
%lf 十進位制浮點數(double)
%o 八進位制數
%s 字串
%u 無符號十進位制數
%x 十六進位制數
2.itoa函式
char *itoa(int value, char* string, int radix),不過與平臺相關,一般不使用。
3.Format函式(double/float->CString)MFC
CString.Format("%.3lf",data)
4.ostringstream類<sstream>
ostringstream os;
double a=123.4;
os<<a;
cout<<os.str();
字串轉數字
1.sscanf_s函式
char str[] = "123.321";
double a;
sscanf_s(str, "%lf", &a) ;
cout << "a的字串表示:" << a;
2.atoi/atol/atof函式
atoi:轉換為整型,atol:轉換為長整型,atof:轉換為浮點型別
3.istringstream類<sstream>
istringstream is;
char str[]="123.45";
double a;
is.str(str);
is>>a;
cout<<a;