C++整数と文字列の相互回転
4835 ワード
C++整数と文字列の相互回転
flyfish
文字列整列
Cの方法cstrはchar*またはconst char*タイプの文字列int num=atoi(str)である.int num = strtol(cstr, NULL, 10);
//10表示進数
C++11の方法
結果出力std::stoi("1")is 1 std::stoi("1.5")is 1 std::stoi("1 with words")is 1
//ソースコード参考cplusplus.com
出力2001,A Space Odyssey:2001 and[,A Space Odyssey]40 c 3:16579-10010110001:-1201 x 7 f:127
その他のタイプは符号なし整数stoulに似ています
浮動小数点型stof
数値回転文字列std::string s;s = std::to_string(1) + ” is int, “;
その他の数値タイプはs=std::to_に似ています.string(3.14f) + ” is float.”;
flyfish
文字列整列
Cの方法cstrはchar*またはconst char*タイプの文字列int num=atoi(str)である.int num = strtol(cstr, NULL, 10);
//10表示進数
C++11の方法
void test1()
{
std::string str1 = "1";
std::string str2 = "1.5";
std::string str3 = "1 with words";
int myint1 = std::stoi(str1);
int myint2 = std::stoi(str2);
int myint3 = std::stoi(str3);
std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '
';
std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '
';
std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '
';
}
結果出力std::stoi("1")is 1 std::stoi("1.5")is 1 std::stoi("1 with words")is 1
//ソースコード参考cplusplus.com
void test2()
{
std::string str_dec = "2001, A Space Odyssey";
std::string str_hex = "40c3";
std::string str_bin = "-10010110001";
std::string str_auto = "0x7f";
std::string::size_type sz; // alias of size_t
int i_dec = std::stoi (str_dec,&sz);
int i_hex = std::stoi (str_hex,nullptr,16);
int i_bin = std::stoi (str_bin,nullptr,2);
int i_auto = std::stoi (str_auto,nullptr,0);
std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]
";
std::cout << str_hex << ": " << i_hex << '
';
std::cout << str_bin << ": " << i_bin << '
';
std::cout << str_auto << ": " << i_auto << '
';
return 0;
}
出力2001,A Space Odyssey:2001 and[,A Space Odyssey]40 c 3:16579-10010110001:-1201 x 7 f:127
その他のタイプは符号なし整数stoulに似ています
浮動小数点型stof
数値回転文字列std::string s;s = std::to_string(1) + ” is int, “;
その他の数値タイプはs=std::to_に似ています.string(3.14f) + ” is float.”;