【原標(biāo)題:offsettop前端開發(fā)這么多年 stringstream字符串與數(shù)字轉(zhuǎn)換】財(cái)金網(wǎng)消息 本文總結(jié)了四種字符串和數(shù)字相互轉(zhuǎn)換的方法,方法一和方法二是c++中的方法,方法三和方法四是C語言庫函數(shù)的方法。
方法一:c++11中string中添加了下面這些方法幫助完成字符串和數(shù)字的相互轉(zhuǎn)換
stod stof stoi stol stold stoll stoul stoull
函數(shù)原型:float stof (const string& str, size_t* idx = 0);
to_string to_wstring
函數(shù)原型:string to_string (float val);
#include#includeusing namespace std;int main() { cout << stof("123.0") <<endl; size_t pos; cout << stof("123.01sjfkldsafj",&pos) <<endl; cout << pos << endl; cout << to_string(123.0) << endl; return 0;}
方法二:C++中使用字符串流stringstream來做類型轉(zhuǎn)化。stingstream能將任何類型輕松轉(zhuǎn)變?yōu)樽址愋?,也能將字符串類型轉(zhuǎn)變?yōu)閿?shù)字類型。有點(diǎn)類似中的sprintf和sscanf函數(shù),但是stringstream操作更加的安全、不會(huì)產(chǎn)生數(shù)組溢出等問題,而且操作簡(jiǎn)單。注意stringstream不會(huì)主動(dòng)釋放內(nèi)存,要使用clear()函數(shù)釋放內(nèi)存。
#include#include#includeusing namespace std;int main() { ostringstream os; float fval = 123.0; os << fval; cout << os.str() << endl; istringstream is("123.01"); is >> fval; cout << fval << endl; return 0;}
三、C語言中的stdio.h中的sprintf、sscanf
sprintf 字符串格式化命令,主要功能是把格式化的數(shù)據(jù)寫入某個(gè)字符串中。sprintf 是個(gè)變參函數(shù)。
sscanf 讀取格式化的字符串中的數(shù)據(jù)。
1、可以用sprintf函數(shù)將數(shù)字轉(zhuǎn)換成字符串
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); // 將整數(shù)轉(zhuǎn)換成字符串time_str=ctime; // 結(jié)果
2、與sprintf對(duì)應(yīng)的是sscanf函數(shù), 可以將字符串轉(zhuǎn)換成數(shù)字
char str[] = "15.455";int i;float fp;sscanf( str, "%d", &i ); // 將字符串轉(zhuǎn)換成整數(shù) i = 15sscanf( str, "%f", &fp ); // 將字符串轉(zhuǎn)換成浮點(diǎn)數(shù) fp = 15.455000printf( "Integer: = %d ", i+1 );printf( "Real: = %f ", fp+1 );return 0;輸出如下:Integer: = 16Real: = 16.455000
四、C標(biāo)準(zhǔn)庫stdlib.h中的atoi, atof, atol, atoll 函數(shù)
1、itoa函數(shù)
char *itoa(int value, char *string, int radix);
value: 待轉(zhuǎn)化的整數(shù)。
radix: 是基數(shù)的意思,即先將value轉(zhuǎn)化為radix進(jìn)制的數(shù),范圍介于2-36,比如10表示10進(jìn)制,16表示16進(jìn)制。
* string: 保存轉(zhuǎn)換后得到的字符串。
返回值:
char * : 指向生成的字符串, 同*string。
備注:該函數(shù)的頭文件是"stdlib.h"
2. atoi
C語言庫函數(shù)名: atoi
功 能: 把字符串轉(zhuǎn)換成整型數(shù)
函數(shù)說明: atoi()會(huì)掃描參數(shù)nptr字符串,檢測(cè)到第一個(gè)數(shù)字或正負(fù)符號(hào)時(shí)開始做類型轉(zhuǎn)換,之后檢測(cè)到非數(shù)字或結(jié)束符 \0 時(shí)停止轉(zhuǎn)換,返回整型數(shù)。
原型: int atoi(const char *nptr);
需要用到的頭文件: #include