1. 程式人生 > >C++ int與string的相互轉換

C++ int與string的相互轉換

strings 構造函數 size 三種 浮點型 cout int 成員 文件

一、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 Output 14 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的相互轉換