logo

C++ の Stoi 関数

立っている です C++標準ライブラリ 文字列を整数に変換する関数。の略です '文字列を整数に変換' 。文字列を入力として受け取り、対応する整数値を返します。この関数は、次のタイプの例外を発生させることができます。 std::invalid_argument 入力文字列が有効な整数を表していない場合。

C++ での stoi の使用例:

 #include #include int main() { std::string str1 = '123'; int num1 = std::stoi(str1); std::cout<< num1 << std::endl; // Output: 123 std::string str2 = '-456'; int num2 = std::stoi(str2); std::cout<< num2 << std::endl; // Output: -456 std::string str3 = '7.89'; try { int num3 = std::stoi(str3); } catch (std::invalid_argument&e) { std::cout<< 'Invalid argument: ' << str3 << std::endl; } return 0; } 

出力

 123 -456 

最初の例では、文字列 「123」 整数に変換されます 123 。 2 番目の例では、文字列 「-456」 整数に変換されます -456 。 3 番目の例では、文字列「7.89」は有効な整数ではないため、 std::invalid_argument 例外がスローされます。

その他のコード スニペットの例:

 #include #include int main() { std::string str1 = '100'; int num1 = std::stoi(str1); std::cout<< num1 << std::endl; // Output: 100 std::string str2 = '200'; int num2 = std::stoi(str2, 0, 16); std::cout<< num2 << std::endl; // Output: 512 std::string str3 = '300'; int num3 = std::stoi(str3, nullptr, 8); std::cout<< num3 << std::endl; // Output: 192 std::string str4 = 'abc'; try { int num4 = std::stoi(str4); } catch (std::invalid_argument&e) { std::cout<< 'Invalid argument: ' << str4 << std::endl; } return 0; } 

出力

 100 512 192 Invalid argument: abc 

最初の例では文字列を変換します。 「100」 10進数の整数に 100 。 2 番目の例では、文字列 「200」 16 進整数に変換されます 512 通り過ぎて 0 2 番目の引数として、 16 の 3 番目の引数として 立っている

3 番目の例では、文字列 「300」 8進整数に変換されます 192 通り過ぎて nullptr 2 番目の引数として、 8 stoi の 3 番目の引数として。

4 番目の例では、文字列 「ABC」 は有効な整数ではないため、 std::invalid_argument 例外がスローされます。