C++ で文字列から double 型に変換する方法

C++では、std::stod関数を用いて文字列をdouble型に変換することができます。この関数は文字列を引数として取り、その文字列と同等のdouble値を返します。

サンプルコードを以下に示します。

#include <iostream>
#include <string>

int main() {
    std::string str = "3.14159";
    double number = std::stod(str);
    
    std::cout << "转换后的double值: " << number << std::endl;
    
    return 0;
}

日本語で自然に言い換えると、次のようになります。

转换后的double值: 3.14159

std::stod関数を使用する際は文字列が有効なdouble値に変換できない場合にstd::invalid_argument例外が発生することから、例外処理を付与するのが良い。

广告
広告は10秒後に閉じます。
bannerAds
bannerAds