好久沒有寫C++程式了,感覺陌生了好多,單是一個int和string的互相轉換就搞了老半天,為了方便以後的工作,將它們寫下來以供參考。
1.int轉成string
a、使用stringstream對象:
1: #include <iostream>
2: #include <string>
3: #include <sstream>
4: using namespace std;
5: int main(){
6: stringstream ss;
7: int result=1000;
8: string str;
9: ss<<result;
10: ss>>str;
11: cout<<str<<endl;
12: return 0;
13: }
b、使用sprintf函數,函數原型:int sprintf( char *buffer, const char *format [, argument] ... ),轉換
後的字串儲存在buffer中,format的使用類似於printf函數,後邊的選擇性參數就是需要轉換的參數,樣本如下:
1: #include <iostream>
2: #include <string>
3: #include <sstream>
4: using namespace std;
5: int main(){
6: int result=1000;
7: char buffer[100];
8: sprintf(buffer,"%d",result);
9: string str(buffer);
10: cout<<str<<endl;
11: return 0;
12: }
c、使用itoa函數,使用方法類似於sprintf函數,函數原型:char *_itoa( int value, char *buffer, int radix ),
value表示要轉換的整數,buffer儲存轉換後的字串,radix是基數,也就是要轉換成進位,一般是十進位,樣本如下:
1: #include <iostream>
2: #include <string>
3: #include <sstream>
4: using namespace std;
5: int main(){
6: int result=1000;
7: char buffer[100];
8: itoa(result,buffer,10);
9: string str(buffer);
10: cout<<str<<endl;
11: return 0;
12: }
d、使用宏定義,這個方法很靈活,也可以轉換其他資料類型的資料,樣本如下:
1: #include <iostream>
2: #include <string>
3: #define toString(x) #x
4: using namespace std;
5: int main(){
6: int result=1000;
7: string str=toString(result);
8: cout<<str<<endl;
9: return 0;
10: }
以上所有的輸出都是1000
2.string轉int
a、使用stringstream對象,使用方法和int轉string類似,樣本如下所示:
1: #include <iostream>
2: #include <string>
3: #include <sstream>
4: using namespace std;
5: int main(){
6: stringstream ss;
7: string str="1000";
8: int result;
9: ss<<str;
10: ss>>result;
11: cout<<result<<endl;
12: return 0;
13: }
b、使用atoi函數,函數原型:int atoi ( const char * str ),使用這個函數之前必須先把string對象調用c_str()函數,
樣本如下:
1: #include <iostream>
2: #include <string>
3: using namespace std;
4: int main(){
5: string str="1000";
6: const char *pstr=str.c_str();
7: int result=atoi(pstr);
8: cout<<result<<endl;
9: return 0;
10: }
以上所有的輸出都是1000。
本文所有樣本程式都在vs2008下測試通過。