【问题标题】:Checking the int limits in stoi() function in C++ [duplicate]在 C++ 中检查 stoi() 函数中的 int 限制 [重复]
【发布时间】:2013-09-03 05:59:51
【问题描述】:

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

【问题讨论】:

  • 为什么不捕获异常并相应地处理呢?
  • 您可能想阅读参考such as this,了解当解析字符串出现问题时会发生什么。
  • 非常感谢大家!是的,我将通过参考!

标签: c++ string int bounds


【解决方案1】:

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

#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

【讨论】:

    【解决方案2】:

    捕捉异常:

    string y = "2323298347293874928374927392374924"
    int x;
    
    try {
      x = stoi(y);
    }
    catch(...) {
      // String could not be read properly as an int.
    }
    

    【讨论】:

      【解决方案3】:

      如果字符串表示的值太大而无法存储在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.
      

      【讨论】:

      • 不适合long long怎么办?
      • 如果它不适合 long long 它不是一个有效的整数值(忽略扩展整数类型),你会得到一个例外。
      • 你也可以尝试直接转换成int或者想要的类型。
      • @NeilKirk - 不,这不符合原始要求,即检测它是否适合int。但我已经改变了超出范围的行为以使其更清晰。
      猜你喜欢
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 2014-10-02
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多