菜鸟笔记
提升您的技术认知

stoi函数用法总结

stoi函数

作用是将 n 进制的字符串转化为十进制,使用时包含头文件string.
定义如下:

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

参数:
str - 待转换的字符
pos - 其取值可以是一个空字符,在这种情况下,pos未被使用;另外如果pos不是空指针,函数将pos的值设置为str中数字后面的第一个字符的位置。
base - 字符中数字的进制,默认为10进制,如果base取值为0,则进制由字符串中的格式决定。

返回值:
如果转换成功的话,stoi函数将会把转换后的得到数字以int类型返回。
如果字符串中没有数字的话,将会抛出"invalid_argument"的异常
如果字符串中的数字转换后超过int的范围,将会抛出"out_of_range"的异常
因此使用stoi函数的时候最好加入异常处理。

例程如下:

#include <string>
#include <iomanip>
#include <utility>
#include <iostream>
#include <stdexcept>
 
int main()
{
  
    const auto data = {
  
        "45",
        "+45",
        " -45",
        "3.14159",
        "31337 with words",
        "words and 2",
        "12345678901",
    };
 
    for (const std::string s : data)
    {
  
        std::size_t pos{
  };
        try
        {
  
            std::cout << "std::stoi('" << s << "'): ";
            const int i {
  std::stoi(s, &pos)};
            std::cout << i << "; pos: " << pos << '\n';
        }
        catch(std::invalid_argument const& ex)
        {
  
            std::cout << "std::invalid_argument::what(): " << ex.what() << '\n';
        }
        catch(std::out_of_range const& ex)
        {
  
            std::cout << "std::out_of_range::what(): " << ex.what() << '\n';
            const long long ll {
  std::stoll(s, &pos)};
            std::cout << "std::stoll('" << s << "'): " << ll << "; pos: " << pos << '\n';
        }
    }
 
    std::cout << "\nCalling with different radixes:\n";
    for (const auto& [s, base]: {
   std::pair<const char*, int>
        {
  "11",  2}, {
  "22",  3}, {
  "33",  4}, {
  "77",  8},
        {
  "99", 10}, {
  "FF", 16}, {
  "jJ", 20}, {
  "Zz", 36}, })
    {
  
        const int i {
  std::stoi(s, nullptr, base)};
        std::cout << "std::stoi('" << s << "', " << base << "): " << i << '\n';
    }
}

输出为:

std::stoi('45'): 45; pos: 2
std::stoi('+45'): 45; pos: 3
std::stoi(' -45'): -45; pos: 4
std::stoi('3.14159'): 3; pos: 1
std::stoi('31337 with words'): 31337; pos: 5
std::stoi('words and 2'): std::invalid_argument::what(): stoi
std::stoi('12345678901'): std::out_of_range::what(): stoi
std::stoll('12345678901'): 12345678901; pos: 11
 
Calling with different radixes:
std::stoi('11', 2): 3
std::stoi('22', 3): 8
std::stoi('33', 4): 15
std::stoi('77', 8): 63
std::stoi('99', 10): 99
std::stoi('FF', 16): 255
std::stoi('jJ', 20): 399
std::stoi('Zz', 36): 1295