10

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

3 回答 3

20

您可以使用异常处理机制:

#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
}

stoi 函数的详细描述以及如何处理错误

于 2013-08-30T13:28:34.620 回答
3

捕捉异常:

string y = "2323298347293874928374927392374924"
int x;

try {
  x = stoi(y);
}
catch(...) {
  // String could not be read properly as an int.
}
于 2013-08-30T13:28:37.737 回答
0

如果字符串表示的值太大而无法存储在 中int,则将其转换为更大的值并检查结果是否适合于int

long long temp = stoll(y);
if (std::numeric_limits<int>::max() < temp
    || temp < std::numeric_limits<int>::min())
    throw my_invalid_input_exception();
int i = temp; // "helpful" compilers will warn here; ignore them.
于 2013-08-30T13:45:58.470 回答