天天看點

c++ string、int互相轉換

采用sstream中定義的字元串流對象來實作

1> int轉string

#include<sstream>
int i = 12; 
ostringstream os; //構造一個輸出字元串流,流内容為空 
os << i; //向輸出字元串流中輸出int整數i的内容 
string str=os.str();  
           

2>string 轉int

string str="123";
istringstream is(str); //構造輸入字元串流,流的内容初始化為“12”的字元串 
int i; 
is >> i; //從is流中讀入一個int整數存入i中