C++ int類型和string類型的相互轉換

來源:互聯網
上載者:User

好久沒有寫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下測試通過。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.