This question already has answers here:
c++ parse int from string [duplicate]

(5个答案)


7年前关闭。




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

10-11 15:01