我该如何解决它?libc++abi.dylib:以 std::invalid_argument 类型的未捕获异常终止:s

How can I fix it? libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion

本文关键字:argument 类型 invalid std 异常终止 何解决 解决 dylib libc++abi      更新时间:2023-10-16
#define REP(i,a,b) for(int i = a; i < b; i++)
#define FOR(i,n) REP(i,0,n)
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string>
using namespace std;

下面的函数是通过字符串方法总结两个大整数的函数。输入可以大于长整型的限制。

string string_add(string a, string b) {
    string new_str = "";
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    string long_s;
    string short_s;
    if (a.size() >= b.size()) {
        long_s = a;
        short_s = b;
    }
    else{
        long_s = b;
        short_s = a;
    }
    int carry = 0;
    int dif = long_s.size() - short_s.size();
    FOR(i, dif)
        short_s += "0";
    FOR(i, long_s.size()) {
        int hab = stoi(long_s.substr(i, 1)) + stoi(short_s.substr(i, 1)) + carry;
        if (hab > 9) {
            carry = 1;
            hab -= 10;
        }
        else carry = 0;
        new_str += to_string(hab);
    }
    if (carry != 0) new_str += to_string(carry);
    reverse(new_str.begin(), new_str.end());
    return new_str;
}

下面是主要部分。

int main() {
    while(!cin.eof()){
        int n;
        string dp[251];
        cin >> n;
        dp[0] = 1;
        dp[1] = 1;
        REP(i,2,n)
            dp[i] = string_add(string_add(dp[i-2], dp[i-2]), dp[i-1]);
        cout << dp[n];
    }
    return 0;
}

问题

如何修复此错误?我认为问题是"stoi"的输入。但我不知道如何解决它。请帮忙。

来自 cpp首选项:

例外:std::invalid_argument 如果无法执行转换

看起来您正在操作的字符串之一无法转换为整数,因此stoi引发异常。 一般来说,了解你正在调用的函数的所有失败模式是个好主意——你需要通过在程序逻辑中的某个地方捕获此异常来处理这种情况(或者保证发送到stoi的字符串始终是可转换的,这在某些用例中可能是可能的)。