轉換為整數浮點數型別
包含數字的 std::string
可以使用轉換函式轉換為整數型別或浮點型別。
***請注意,***所有這些函式在遇到非數字字元時都會停止解析輸入字串,因此 123abc
將轉換為 123
。
std::ato*
系列函式將 C 風格的字串(字元陣列)轉換為整數或浮點型別:
std::string ten = "10";
double num1 = std::atof(ten.c_str());
int num2 = std::atoi(ten.c_str());
long num3 = std::atol(ten.c_str());
Version >= C++ 11
long long num4 = std::atoll(ten.c_str());
但是,不鼓勵使用這些函式,因為如果它們無法解析字串,它們將返回 0
。這很糟糕,因為 0
也可能是有效的結果,例如輸入字串為 0
,因此無法確定轉換是否實際失敗。
較新的 std::sto*
系列函式將 std::string
s 轉換為整數或浮點型別,如果它們無法解析輸入,則丟擲異常。如果可能,你應該使用這些功能 :
Version >= C++ 11
std::string ten = "10";
int num1 = std::stoi(ten);
long num2 = std::stol(ten);
long long num3 = std::stoll(ten);
float num4 = std::stof(ten);
double num5 = std::stod(ten);
long double num6 = std::stold(ten);
此外,與 std::ato*
系列不同,這些函式還處理八進位制和十六進位制字串。第二個引數是指向輸入字串中的第一個未轉換字元的指標(此處未示出),第三個引數是要使用的基數。0
是自動檢測八進位制(從 0
開始)和十六進位制(從 0x
或 0X
開始),任何其他值是使用的基礎
std::string ten = "10";
std::string ten_octal = "12";
std::string ten_hex = "0xA";
int num1 = std::stoi(ten, 0, 2); // Returns 2
int num2 = std::stoi(ten_octal, 0, 8); // Returns 10
long num3 = std::stol(ten_hex, 0, 16); // Returns 10
long num4 = std::stol(ten_hex); // Returns 0
long num5 = std::stol(ten_hex, 0, 0); // Returns 10 as it detects the leading 0x