首页 > 解决方案 > 在创建堆栈数据结构时使用 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

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

标签: c++data-structuresstack

解决方案


您没有显示您的输入的实际外观,但如果它与此问题中显示的输入类似,则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对象,这不是您想要发生的。这段代码: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;
        }
    }
}

推荐阅读