c++ - 在 C++ 中检查 stoi() 函数中的 int 限制

标签 c++ string int bounds

<分区>

我得到了一个字符串 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

关于c++ - 在 C++ 中检查 stoi() 函数中的 int 限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18534036/

相关文章:

c++ - 在 Visual Studio 中执行单个 Boost Test 单元测试

Java,scan double只接受int

c++ - std::set 和 < 运算符重载的奇怪行为?

c++ - Clang AST 访问者,避免遍历包含文件

c - C中字符的值

c - 分别打印字符串中的偶数奇数字符

java - 如何将随机 int 转换为 String 以在 if/else 中使用?

python - 在 Python turtle 事件处理程序中比较坐标时出现 TypeError

c++ - 理解#includes C++

linq - 在C#中使用Linq进行字符串替换