くうと徒然なるままに

モバイルアプリを作りながらバックエンドも作っています。

C++でstd::stringをint float char[]などに変換する方法

自己紹介

こんにちは、もうすぐ高校を卒業してしまうくぅです!
今回は、タイトルにもある通りstd::string を色々な型に変換していきたいと思います。
結構単純だけど、覚えにくいかも?
一応C++11〜です。

環境

std::string → int

std::string str = "123";  
int hoge = stoi(str);   

エラー処理も入れてみた

    std::string str = "123";
    try {
        int i = std::stoi(str);
    } catch (std::invalid_argument e) {
        printf("数値への変換が行われませんでした。");
    } catch (std::out_of_range e) ilife blog{
        printf("引数を間違えています。");
    }

std::string → float

std::string str2 = "0.5";
float f2 = std::stof(str2);

こちらもエラー処理を入れてみた

std::string str = "0.5";
try {
   float f = std::stof(str);
   printf("%f\r\n",f);
} catch (std::invalid_argument) {
   printf("float への変換が失敗しました");
} catch (std::out_of_range) {
   printf("引数が異常です。");
}

std::string → char[]

std::string Hellostring = "Hello World";
char str[256];
sprintf(str, "%s", Hellostring.c_str());

こちらもエラー処理を入れてみた

std::string HelloString = "HelloWorld";
char str[256];
if (EOF == sprintf(str, "%s",HelloString.c_str())) {
    printf("変換に失敗しました。");
}