You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

加密程序出现std::out_of_range错误求助及代码优化建议

Hey there, let's break down this std::out_of_range issue you're hitting with stoi, and then dive into some code improvements too.

First: Why the std::out_of_range Error Happens

The stoi function has a strict limit—it only converts strings that fit within the range of a standard int (usually -2147483648 to 2147483647). Your error is almost certainly coming from one of two scenarios:

  • Either szTempX or qkey represents a number that’s already outside the int range, so converting it with stoi immediately throws.
  • Or the result of stoi(szTempX) - stoi(qkey) exceeds the int range, even if both individual values are valid.

Even if you think your input is "合适", it’s easy to overlook that larger numbers (or their differences) can blow past int’s limits without you noticing.

Fixes for the Overflow Issue

Here are a few practical solutions to resolve the error:

  1. Use larger integer types for conversion
    Swap stoi for stoll (which converts to long long—a much bigger range) to handle larger values, then validate if you need to shrink back to int later:
    try {
        long long tempX = stoll(szTempX);
        long long key = stoll(qkey);
        long long number = tempX - key;
        
        // If you need an int, check the range first
        if (number < INT_MIN || number > INT_MAX) {
            throw std::out_of_range("Calculated value exceeds int range");
        }
        int final_number = static_cast<int>(number);
        // Rest of your logic
    } catch (const std::out_of_range& e) {
        std::cerr << "Overflow error: " << e.what() << "\n";
    } catch (const std::invalid_argument& e) {
        std::cerr << "Invalid number input: " << e.what() << "\n";
    }
    
  2. Use non-throwing conversion for more control
    C++11 introduced std::from_chars, which avoids exceptions and returns explicit error codes instead. This is great for tight, controlled error handling:
    int tempX, key;
    auto [ptr1, ec1] = std::from_chars(szTempX.data(), szTempX.data() + szTempX.size(), tempX);
    auto [ptr2, ec2] = std::from_chars(qkey.data(), qkey.data() + qkey.size(), key);
    
    if (ec1 == std::errc::result_out_of_range || ec2 == std::errc::result_out_of_range) {
        std::cerr << "Error: Input number is too big/small for int\n";
        return;
    }
    if (ec1 != std::errc() || ec2 != std::errc()) {
        std::cerr << "Error: Invalid integer format\n";
        return;
    }
    
    int number = tempX - key;
    
  3. Add pre-conversion input checks
    Before even converting, validate that the input string is a valid integer and doesn’t exceed int length limits (e.g., no more than 10 digits for positive numbers, 11 for negatives):
    bool is_safe_for_int(const std::string& s) {
        if (s.empty()) return false;
        size_t len = s.size();
        if (s[0] == '+' || s[0] == '-') {
            if (len > 11) return false;
            return len <= 11 && (len < 11 || s <= "-2147483648" || s <= "2147483647");
        } else {
            if (len > 10) return false;
            return len <= 10 && s <= "2147483647";
        }
    }
    

Code Criticism & Optimization Tips

Let’s go over some ways to make your code more robust and readable:

  • Missing error handling: Your original code doesn’t catch exceptions from stoi, so it crashes immediately. Always wrap risky operations like string-to-int conversion in try-catch blocks to handle errors gracefully.
  • Unclear variable names: szTempX and qkey are vague—sz usually implies a size, but these are strings. Rename them to something like input_value_str and encryption_key_str to make your code self-documenting.
  • Type rigidity: If your encryption logic deals with potentially large numbers, use long long as your default integer type instead of int to avoid constant overflow risks.
  • Lack of input validation: Before converting, check that the input isn’t empty, has no non-numeric characters (except leading +/-), and fits within your target type’s range. This catches bad input early instead of letting it trigger exceptions later.
  • Modularity: Split your code into small, focused functions (e.g., validate_input(), convert_to_safe_int(), perform_encryption()) instead of lumping everything together. This makes testing and debugging way easier.

内容的提问来源于stack exchange,提问作者HatBreakingDaddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:55:43