C++ stoi Function: String to Integer

The function std::stoi() in C++ is used to convert a string into an integer. Its function prototype is as follows:

int stoi(const string& str, size_t* pos = 0, int base = 10);

Explanation of parameters:

  1. str: represents the string to be converted.
  2. optional parameter, a pointer to an object, is used to store the position following the last character of the converted string.
  3. Base: Optional parameter indicating the number system to be used, defaulting to base 10.

Return value: Return the converted integer value.

Example of use:

#include <iostream>
#include <string>

int main() {
    std::string str = "12345";
    int num = std::stoi(str);
    std::cout << "转换后的整数为: " << num << std::endl;
    return 0;
}

Output result:

转换后的整数为: 12345

Important notes:

  1. If the input string cannot be converted to a valid integer, std::stoi() will throw a std::invalid_argument exception.
  2. std::stoi() throws a std::out_of_range exception if the converted integer exceeds the range of the integer type.
bannerAds