C++(stoi())



std::stoi() 是 C++11 引入的一个标准库函数,用于将字符串转换为整数。与 atoi() 不同,stoi() 提供了更强的功能,包括错误处理、支持指定进制等。

1. 函数

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

1.1 参数

  • str:一个 std::string 或 C 风格字符串 (const std::string&),表示待转换的数字字符串。
  • pos:可选参数,是一个指向 size_t 类型的指针,用于存储字符串中第一个无法转换的字符的索引位置。如果转换成功,pos 会指向该字符的索引。如果不需要这个功能,可以将其设为 nullptr(默认值)。
  • base:可选参数,指定要转换的进制,默认值为 10(即十进制)。stoi 支持 2 到 36 的进制。

1.2 返回值

  • 返回字符串中表示的整数值。
  • 如果字符串中的数字超出了 int 类型的范围,stoi 会抛出 std::out_of_range 异常。

1.3 异常

std::stoi 提供了异常处理机制:

  • std::invalid_argument:如果输入的字符串不包含可转换的数字。
  • std::out_of_range:如果字符串中表示的数字超出了 int 类型的表示范围。


2. 示例

#include <iostream>
#include <string>  // 包含 std::stoi
#include <stdexcept>  // 包含异常类

int main() {
    try {
        std::string str1 = "1234";
        std::string str2 = "56abc";
        std::string str3 = "abc123";
        std::string str4 = "4294967296";  // 超出 int 范围
        
        int num1 = std::stoi(str1);  // 转换为整数 1234
        int num2 = std::stoi(str2);  // 转换为整数 56,遇到非数字字符后停止
        // int num3 = std::stoi(str3);  // 抛出 std::invalid_argument 异常
        // int num4 = std::stoi(str4);  // 抛出 std::out_of_range 异常
        
        std::cout << "num1: " << num1 << std::endl;
        std::cout << "num2: " << num2 << std::endl;
        
    } catch (const std::invalid_argument& e) {
        std::cerr << "Invalid argument: " << e.what() << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Out of range: " << e.what() << std::endl;
    }
    
    return 0;
}

输出:

num1: 1234
num2: 56

2.1 使用 base 参数

std::stoibase 参数允许你转换不同进制的字符串。例如,你可以使用 base = 16 来转换十六进制数,或者 base = 2 来转换二进制数:

#include <iostream>
#include <string>

int main() {
    std::string hexStr = "1A";
    std::string binStr = "1101";
    
    int hexNum = std::stoi(hexStr, nullptr, 16);  // 十六进制转换
    int binNum = std::stoi(binStr, nullptr, 2);   // 二进制转换
    
    std::cout << "Hexadecimal 1A to decimal: " << hexNum << std::endl;
    std::cout << "Binary 1101 to decimal: " << binNum << std::endl;

    return 0;
}

输出:

Hexadecimal 1A to decimal: 26
Binary 1101 to decimal: 13

2.2 pos 参数的使用

pos 参数用于跟踪解析到字符串的哪一部分:

#include <iostream>
#include <string>

int main() {
    std::string str = "123abc456";
    size_t pos;
    int num = std::stoi(str, &pos);  // num 为 123,pos 为 3("abc456" 的位置)
    
    std::cout << "Number: " << num << ", Position: " << pos << std::endl;

    return 0;
}

输出:

Number: 123, Position: 3


3. 总结

  • std::stoi 是一个功能强大的字符串转换函数,支持多种进制、错误处理和字符串解析位置的跟踪。
  • 相比 atoi,它提供了更安全和灵活的方式来处理字符串转换,尤其是在需要处理复杂输入和错误时。


posted @   做梦当财神  阅读(1127)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-08-23 数据降维
点击右上角即可分享
微信分享提示