stoi C++

std::stoi 是 C++11 引入的一个标准库函数,它用于将字符串转换为整数。这个函数定义在头文件 <string> 中。std::stoi 函数尝试将字符串参数转换为一个 int 类型的值。如果转换成功,它会返回转换后的整数值;如果转换失败,它会抛出一个 std::invalid_argument 异常。

std::stoi 函数的基本用法如下

用法:

#include <iostream>  
#include <string>  
  
int main() {  
    std::string str = "123";  
    try {  
        int num = std::stoi(str);  
        std::cout << "转换后的整数是: " << num << std::endl;  
    } catch (std::invalid_argument const &e) {  
        std::cerr << "无效的参数: " << e.what() << '\n';  
    } catch (std::out_of_range const &e) {  
        std::cerr << "数值超出范围: " << e.what() << '\n';  
    }  
    return 0;  
}

在上面的例子中,std::stoi 尝试将字符串 "123" 转换为整数,并成功转换。如果字符串不能被转换为一个整数(例如,如果它包含非数字字符),则会抛出 std::invalid_argument 异常。如果转换后的数值超出了 int 类型能表示的范围,则会抛出 std::out_of_range 异常。

std::stoi 函数还有一些变体,例如 std::stol(转换为 long)、std::stoll(转换为 long long)、std::stoul(转换为 unsigned long)、std::stoull(转换为 unsigned long long),它们提供了更多的灵活性来处理不同大小和符号的整数类型。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

beiqianqian

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值