首页 > 解决方案 > 使用 to_string、reverse、stoi 组合的 C++ 反转数给出运行时错误实例超出范围

问题描述

由于实例超出范围异常而无法解决运行时错误。我将 int 转换为字符串,反转字符串并使用 stoi 将其返回到 int。简单的测试数字完全反转,但更大的数字超出范围。不确定在代码中的哪个位置调整超出范围的异常。超级卡,求大神帮忙。

int reverse(int x) {

    bool negFlag = false;
    if(x < 0)
    {
        negFlag = true;
    }

    string xString = std::to_string(abs(x));
    std::reverse(xString.begin(), xString.end());
    int xNum = std::stoi(xString);

    return (negFlag == true)? -xNum: xNum;
}

这是返回的错误:

terminate called after throwing an instance of 'std::out_of_range'
what():  stoi
Last executed input:  1534236469

较小的数字效果很好。

Your input: 123
Output:     321
Expected:   321

我的字符串末尾是否有一个 \0 会在转换中丢弃所有内容?这些 C++ 方法的新手。非常感谢。真的很想确定这些方法并能够轻松使用它们。

重要信息:

Note: Assume we are dealing with an environment which could only store 
integers within the 32-bit signed integer range: 

[-2 31到 +2 31 -1]

For the purpose of this problem, assume that your function returns 0 when 
the reversed integer overflows.

-->> 不确定如何制定返回 0 的 if 语句;当超过 32 位时。

标签: c++runtime-errorreverseoutofrangeexception

解决方案


的反面1,534,236,4699,646,324,351int典型的 32 位可以容纳的最大值是2,147,483,647,所以它不适合它。

您需要让您的函数返回更大的值,例如long long(至少为 64 位)并为其使用适当的转换函数,例如:

long long reverse(int x) {

    //...

    long long xNum = std::stoll(xString);

    //...

}

您是否也想将输入类型更改为更大的类型,取决于您的函数应该能够处理的最大输入值。


编辑后:

您可以捕获转换错误并0在这种情况下返回(需要#include<stdexcept>):

try {
    int xNum = std::stoi(xString);
    // Maybe insert additional range test according to assignment (?)
    return (negFlag == true)? -xNum: xNum;
} catch(const std::out_of_range&) {
    return 0;
}

假设int是 32 位二进制补码(据我所知,作业试图用值范围提出建议,推测应该是[-2**31, 2**31-1]):

另请注意,您的初始调用absif 具有未定义的行为x == -2**31,因为2**31在 32 位中无法表示int。因此,在调用之前,您需要先为此做一个特殊情况,abs以避免未定义的行为。

同样,您需要考虑函数的结果应该是的情况-2**31。但是您可能会注意到这种情况无关紧要,因为它对应的输入值已经超出了int.


推荐阅读