C++ stoi函数,字符串转整数

stoi函数是C++标准库中的一个函数,用于将字符串转换为整数。

stoi函数的定义如下:

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

参数说明:

- str:要转换的字符串。

- idx:可选参数,用于存储转换结束的位置,即第一个无效字符的位置。

- base:可选参数,指定转换时使用的进制,默认为10进制。

返回值:

- 返回转换后的整数值。

示例如下:

#include <iostream>
#include <string>
int main() {
    std::string str = "12345";
    int num = std::stoi(str);
    std::cout << num << std::endl; // 输出:12345

    str = "1010";
    int binaryNum = std::stoi(str, nullptr, 2);
    std::cout << binaryNum << std::endl; // 输出:10

    str = "123abc";
    size_t idx;
    int result = std::stoi(str, &idx);
    std::cout << result << std::endl; // 输出:123
    std::cout << "Invalid character position: " << idx << std::endl; // 输出:3

    return 0;
}

运行结果:

通过调用stoi函数将字符串转换为整数。第一个示例将字符串"12345"转换为整数12345,第二个示例将字符串"1010"按二进制转换为整数10。第三个示例中,由于字符串"123abc"中包含无效字符"a",转换结束的位置为3,所以只将前面的数字"123"转换为整数123

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值