1.stoi()、stof()、stod() 實現字符串轉 int、float、double。
- stoi -> string to integer
- stof -> string to float
- stod -> string to double
函數原型:
int stoi (const string& str, size_t* idx = 0, int base = 10); //ids: 指明從字符串何處開始轉,base: 轉換成幾進制數
float stof (const string& str, size_t* idx = 0); //ids: 指明從字符串何處開始轉(默認從字符串首字母開始)
double stod (const string& str, size_t* idx = 0); //ids: 指明從字符串何處開始轉(默認從字符串首字母開始)
1 #include<iostream> 2 using namespace std; 3 4 int main() { 5 string s = "3.14"; //數字字符串 6 int i = stoi(s); //字符串轉整型 7 float f = stof(s); //字符串轉浮點型 8 double d = stod(s); //字符串轉雙精度浮點型 9 cout << i << " " << f << " " << d << endl; 10 return 0; 11 }
notes: 字符串中如果含有非數字的字符,則會拋出異常。如果非數字字符在數字字符之后,會自動截取前面的數字字符!
1 #include<iostream> 2 using namespace std; 3 4 int main() { 5 string s = "abc3.14"; //非法數字字符串 6 int i = stoi(s); //字符串轉整型 7 float f = stof(s); //字符串轉浮點型 8 double d = stod(s); //字符串轉雙精度浮點型 9 cout << i << " " << f << " " << d << endl; 10 return 0; 11 }
Error: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
#include<iostream> using namespace std; int main() { string s = "3.14abd#"; //數字字符串,只會截取3.14,abc會拋棄掉! int i = stoi(s); //字符串轉整型 float f = stof(s); //字符串轉浮點型 double d = stod(s); //字符串轉雙精度浮點型 cout << i << " " << f << " " << d << endl; return 0; }
Output: 3 3.14 3.14
2. 數字轉字符串 -- to_string() and stringstream
方法一:通過 to_string(value) 方法
1 int main() { 2 double PI = 3.1415926; 3 string p = "PI is " + to_string(PI); 4 cout << p << endl; 5 return 0; 6 }
方法二:通過 stringstream 字符流操作
1 #include<iostream> 2 #include <sstream> 3 using namespace std; 4 5 int main() { 6 double PI = 3.1415926; 7 stringstream ss; // 聲明一個字符流對象 8 string p; 9 ss << PI; // 將double型數據輸入流中 10 ss >> p; // 將流中數據輸出到字符串中 11 cout << "PI is " << p << endl; 12 return 0; 13 }