溫馨提示×

c++字符串轉數字怎么實現

c++
小億
126
2023-12-05 09:45:12
欄目: 編程語言

在C++中,可以使用std::stoi函數將字符串轉換為整數,使用std::stof函數將字符串轉換為浮點數。

下面是一個示例代碼:

#include <iostream>
#include <string>

int main() {
    std::string str = "12345";
    int num = std::stoi(str);
    std::cout << "轉換后的整數為: " << num << std::endl;

    std::string str2 = "3.14";
    float num2 = std::stof(str2);
    std::cout << "轉換后的浮點數為: " << num2 << std::endl;

    return 0;
}

輸出結果為:

轉換后的整數為: 12345
轉換后的浮點數為: 3.14

需要注意的是,如果字符串無法轉換為對應的數字類型,將會引發std::invalid_argument異常。因此,在實際使用中,需要進行異常處理。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女