c++のstoi関数の使い方は何ですか?
C++のstd::stoi()関数は、文字列を整数に変換するために使用されます。その関数のプロトタイプは以下の通りです。
int stoi(const string& str, size_t* pos = 0, int base = 10);
Explanation of parameters:
パラメータの説明:
- str: 変換する文字列を示す。
- pos:オプションのパラメーターで、変換された文字列の最後の文字の次の位置を格納するためにオブジェクトを指すポインタ。
- ベース:オプションの引数で、使用する基数を表し、デフォルトは10進数です。
返り倩:変換された整数値を返します。
例文:
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout << "转换后的整数为: " << num << std::endl;
return 0;
}
結果を出力します。
转换后的整数为: 12345
注意事項:
- std::stoi()は、文字列を有効な整数に変換できない場合、std::invalid_argument例外をスローします。
- std::stoi()は、変換された整数が整数タイプの範囲を超えると、std::out_of_range例外が投げられます。