加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C [复制]中检查stoi()函数中的int限制

发布时间:2020-12-16 05:19:13 所属栏目:百科 来源:网络整理
导读:参见英文答案 c++ parse int from string 5个 我得到了一个字符串y,其中我确保它只包含数字.在使用stoi函数将其存储在int变量中之前,如何检查它是否超出整数的边界? string y = "2323298347293874928374927392374924"int x = stoi(y); // The program gets
参见英文答案 > c++ parse int from string 5个
我得到了一个字符串y,其中我确保它只包含数字.在使用stoi函数将其存储在int变量中之前,如何检查它是否超出整数的边界?
string y = "2323298347293874928374927392374924"
int x = stoi(y); // The program gets aborted when I execute this as it exceeds the bounds
                 //   of int. How do I check the bounds before I store it?

解决方法

你可以使用异常处理机制:
#include <stdexcept>

std::string y = "2323298347293874928374927392374924"
int x;

try {
  x = stoi(y);
}
catch(std::invalid_argument& e){
  // if no conversion could be performed
}
catch(std::out_of_range& e){
  // if the converted value would fall out of the range of the result type 
  // or if the underlying function (std::strtol or std::strtoull) sets errno 
  // to ERANGE.
}
catch(...) {
  // everything else
}

detailed description of stoi function and how to handle errors

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读