核心思想:
整數轉化為字串:加 『0』 ,然後逆序。
字串轉化整數:減 『0』,乘以10累加。
注:整數加 『0』後會隱性的轉化為char型別;字元減 『0』隱性轉化為int型別
如果用函式實現
c++11 直接to_string(int i)將整形轉為string型別字串
下面的函式轉為字串是char型別
最好用:stringstream
int n = 123456;
char p[100] = {};
stringstream s;
s << n;
s >> p;
其次:springf、sscanf
// 數字轉字串
sprintf(str, 「%d」, num);
// 字串轉數字
sscanf(str, 「%d」, &rsl);
再其次:itoa、atoi
1、數字轉字元
itoa()函式有3個引數:數字、寫入轉換結果的目標字串、進製
itoa(num, string, 10); // 按10進製轉換
2、字元轉數字
char str[4] = ;
int num = atoi(str);
面試自己手寫實現:
1.整數轉字串
2.字串轉整數#include using namespace std;
int main()
// 剛剛轉化的字串是逆序的
while(i >= 0)
cout << str << endl;
return 0;
}
#include using namespace std;
int main() ;
int num = 0;
int i = 0;
while(str[i])
cout << num << endl;
return 0;
}
C C 字串與數字相互轉換
一.利用stringstream類 1.字串到整數 stringstream sstr str int x sstr x 即從sstr中提取資料 2.整數到字串 stringstream sstr int x sstr x string str sstr.str 缺點 處理大量資料轉換速度較慢。st...
C C 數字和字串的轉換
今天,我在做題時候,遇到了字串和數字之間的轉換,現將轉換的方法總結如下。數字轉換成字串 include include using namespace std intmain 字串轉化成數字 include include using namespace std intmain 數字轉換成字串 in...
字元與數字轉換C
字串轉數字 string str 123 const char ch 10 123.3 int a sscanf str 0 d a sscanf ch,lf a 數字轉字串 char ch 10 int a 123 sprintf ch,d a a 123.345 sprintf ch,3lf a...