C++11で数値と文字列の変換

C++11から数値と文字列の変換を簡単にできるようになりました。

数値を文字列に変換する

数値を文字列に変換するには「std::to_string」関数を使用します。

例:std::stringに変換する

int val = 123;
std::string str = std::to_string(val); // "123"

例:std::wstringに変換する

int val = 123;
std::wstring str = std::to_wstring(val); // "123"

文字列をint型に変換する

文字列をint型に変換するには「std::stoi」関数を使用します。

例:文字列をint型に変換する

std::string s = "123";
int i = std::stoi(s); // 123

例:16真数として文字列をint型に変換する

std::string s = "10";
int i = std::stoi(s, nullptr, 16); //16

std::string s = "0xFF";
int i = std::stoi(s, nullptr, 16); //255

例:8真数として文字列をint型に変換する

std::string s = "10";
int i = std::stoi(s, nullptr, 8); //8

文字列をfloat型に変換する

文字列をfloat型に変換するには「std::stof」関数を使用します。

例:文字列をfloat型に変換する

std::string s = "12.3";
float f = std::stof(s); //12.3

例:指数表現の文字列をfloat型に変換する

std::string s = "1.234e2";
float f = std::stof(s); //123.4

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください