C++11中string與數值型別的轉換
阿新 • • 發佈:2020-08-26
C++中string與數值型別的相互轉換記錄
string轉int、double、long
string s = "123.456"; // string -> int cout << stoi(s) << endl; // string -> long cout << stol(s) << endl; // string -> float cout << stof(s) << endl; // string -> double cout << stod(s) << endl;
int、double、long、char轉string
string s = "Test"; // int -> string int i = 7; cout << s + "int:" + to_string(i) << endl; // float -> string float f = 3.14; cout << s + "float:" + to_string(f) << endl; // double -> string double d = 3.1415; cout << s + "double:" + to_string(d) << endl; // char -> string char c = 'z'; cout << s + "char_1:" + to_string(c) << endl; // 需注意,這裡的c是以ASCII數值傳入 cout << s + "char_2:" + c << endl;
綜合以上例子,可總結出:
string 轉換成 數值型別用:sto+型別開頭字母()
函式,例如stroi、strol、strod
等等
數值型別 轉換成 string:用to_string()
,需注意**char型別轉換成string型別是自動轉換,若是用to_string()
函式則會將char視為數值ASCII數值傳入。
參考文章連結https://blog.csdn.net/HiccupHiccup/article/details/62421032