C++ int與string的相互轉換

來源:互聯網
上載者:User

標籤:建立   相互   標頭檔   float   font   除了   color   bsp   對象   

一、int轉換成string

  Ⅰ、to_string函數

c++11標準增加了全域函數std::to_string:

string to_string (int val);

string to_string (long val);

string to_string (long long val);

string to_string (unsigned val);

string to_string (unsigned long val);

string to_string (unsigned long long val);

string to_string (float val);

string to_string (double val);

string to_string (long double val);

Example:

 1 // to_string example   2 #include <iostream>   // std::cout   3 #include <string>     // std::string, std::to_string   4    5 int main ()   6 {   7   std::string pi = "pi is " + std::to_string(3.1415926);   8   std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";   9   std::cout << pi << ‘\n‘;  10   std::cout << perfect << ‘\n‘;  11   return 0;  12 } 13 Output14 pi is 3.141593  15 28 is a perfect number 

  Ⅱ、藉助字串流

  標準庫定義了三種類型字串流:istringstream,ostringstream,stringstream,看名字就知道這幾種類型和iostream中的幾個非常類似,分別可以讀、寫以及讀和寫string類型,它們也確實是從iostream類型派生而來的。要使用它們需要包含sstream標頭檔。

除了從iostream繼承來的操作

  1.sstream類型定義了一個有string形參的建構函式,即:  stringstream stream(s); 建立了儲存s副本的stringstream對象,s為string類型對象

  2.定義了名為str的成員,用來讀取或設定stringstream對象所操縱的string值:stream.str(); 返回stream中儲存的string類型對象stream.str(s); 將string類型的s複製給stream,返回void

Example:

1 int aa = 30;2 stringstream ss;3 ss<<aa; 4 string s1 = ss.str();5 cout<<s1<<endl; // 30

二、string轉換成int

  Ⅰ、採用標準庫中atoi函數,對於其他類型也都有相應的標準庫函數,比如浮點型atof(),long型atol()等等

Example:

1 std::string str = "123";2 int n = atoi(str.c_str());3 cout<<n; //123

  Ⅱ、採用sstream標頭檔中定義的字串流對象來實現轉換

1 istringstream is("12"); //構造輸入字串流,流的內容初始化為“12”的字串   2 int i;   3 is >> i; //從is流中讀入一個int整數存入i中  

 

參考資料:

http://blog.csdn.net/lxj434368832/article/details/78874108

https://www.cnblogs.com/aminxu/p/4704281.html

C++ int與string的相互轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.