1. 程式人生 > >string型別與int型別相互轉換

string型別與int型別相互轉換

string型別轉換int型別

C語言轉換形式:

[plain] view plain copy  print?在CODE上檢視程式碼片派生到我的程式碼片
  1. ...  
  2. std::string str;  
  3. int i = atoi(str.c_str());  
  4. ...  


C++轉換形式(C++11):

[plain] view plain copy  print?在CODE上檢視程式碼片派生到我的程式碼片
  1. ...  
  2. std::string str;  
  3. int i = std::stoi(str);  
  4. ...  

同樣, 可以使用 stol(long), stof(float), stod(double) 等.

int轉string:

int n = 65535;
char t[256];
string s;

sprintf(t, "%d", n);
s = t;
cout << s << endl;