微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在创建堆栈数据结构时使用 stoi 会导致错误

如何解决在创建堆栈数据结构时使用 stoi 会导致错误

我已经创建了一个堆栈数据结构并正在实施它。我一直在使用下面的功能

void Stack::solution(const char *input_path,const char *output_path)
{
    string line;
    Stack tempStack; 
    ifstream myfile(input_path);
    ofstream outfile(output_path);
    
    while (getline(myfile,line)) {
        if (line.substr(0,1) == "s") {
            Stack tempStack = Stack();
        };

        if (line.substr(0,1) == "e") {
            int a = stoi(line.substr(1,1));
            tempStack.push(a);
        };

        if (line.substr(0,1) == "o") {
            int a = stoi(line.substr(1,1));
            int num = tempStack.pop();
            string x = to_string(num);
            outfile <<  x << "";
        };        
    }
}

但问题是代码的这一部分,除非不是:

if (line.substr(0,1) == "o") {
    int a = stoi(line.substr(1,1));
    int num = tempStack.pop();
    string x = to_string(num);
    outfile <<  x << "";
};        

我收到此错误

libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion

Abort trap: 6

我最初认为问题在于我没有将 int num 转换为 string,但即使我有错误也离解决不近了。

解决方法

您没有显示您的输入实际是什么样子,但如果它与 this question 中显示的输入类似,那么 o 情况没有与之关联的整数值,因此对 line.substr(1,1) 的调用不会返回 string 可以转换为 std::stoi()int,因此会抛出 std::invalid_argument 异常。这是有道理的,因为 o 的情况只是从堆栈中弹出一个值,而不是将新值推入堆栈。因此,只需完全删除对 std::stoi() 的调用:

if (line.substr(0,1) == "o") {
    //int a = stoi(line.substr(1,1)); // <-- get rid of this!
    int num = tempStack.pop();
    string x = to_string(num);
    outfile << x;
};        

此外,您在 tempStack 案例的范围内有 2 个 s 对象。您正在创建第二个 Stack 对象,它是 shadowing 现有的 Stack 对象,这不是您想要发生的。这段代码:

Stack tempStack; 
...
if (line.substr(0,1) == "s") {
    Stack tempStack = Stack();
};

应该是这样的:

Stack tempStack; 
...
if (line.substr(0,1) == "s") {
    tempStack = Stack();
};

所以,话虽如此,您的函数应该更像这样:

void Stack::solution(const char *input_path,const char *output_path)
{
    string line;
    Stack tempStack; 
    ifstream myfile(input_path);
    ofstream outfile(output_path);
    
    while (getline(myfile,line)) {
        if (line.substr(0,1) == "s") {
            tempStack = Stack();
        }

        if (line.substr(0,1) == "e") {
            int a = stoi(line.substr(1,1));
            tempStack.push(a);
        }

        if (line.substr(0,1) == "o") {
            int num = tempStack.pop();
            string x = to_string(num);
            outfile << x;
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。