C++——stoi函数

版权声明:本文系原创,转载请声明出处。

 

1. 函数原型

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

 

2. 参数说明

  • str
String object with the representation of an integral number.
  • idx
Pointer to an object of type size_t, whose value is set by the function to position of the next character in  str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.
  • base
Numerical base (radix) that determines the valid characters and their interpretation.
If this is  0, the base used is determined by the format in the sequence (see strtol for details). Notice that by default this argument is  10, not  0.

 

3. 返回值

如果解析成功,返回转换后的整数。

On success, the function returns the converted integral number as an int value.

 

4. 异常处理

stoi当字符串不符合规范时,会抛出异常,所以在使用stoi时应该有必要的异常处理:

#include <stdexcept>
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    std::string y = "253647586946334221002101219955219971002";
    int x;
 
    try {
        x = stoi(y);
    }
    catch (std::invalid_argument&){
        // If no conversion could be performed, an invalid_argument exception is thrown.
        cout << "Invalid_argument" << endl;
    }
    catch (std::out_of_range&){
        // If the value read is out of the range of representable values by an int, an out_of_range exception is thrown.
        cout << "Out of range" << endl;
    }
    catch (...) {
        // everything else
        cout << "Something else" << endl;
    }
    return 0;
}

 

参考资料:

  • https://blog.csdn.net/u014694994/article/details/79074566
  • http://www.cplusplus.com/reference/string/stoi/?kw=stoi

 

转载于:https://www.cnblogs.com/oddcat/p/10273080.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值