函数体前缀表达式求值报错的

代码不能运行,报错

img

#include <fstream>
#include <vector>
#include <iostream>
#include <string>
using namespace std;

bool isDelimiter(char c)
{
    if ((c == '(' || c == ')') || c == ',')
        return true;
    else
        return false;
}

//删除()和,
vector<string> splitString(const string& str)
{
    vector<string> tokens;
    string token;

    for (char c : str) //挨个从str中取并判断是否为分隔符
    {
        if (isDelimiter(c)) {
            if (!token.empty()) {
                tokens.push_back(token);
                token.clear();
            }
        }
        else {
            token += c;
        }
    }
    if (!token.empty())
        tokens.push_back(token);
    return tokens;
}

//前缀求值
int evaluatePrefixExpression(vector<string>& tokens, int& index)
{
    string token = tokens[index];
    if (token == "add" || token == "sub" || token == "muti" || token == "div") {
        int operand1 = evaluatePrefixExpression(tokens, ++index);
        int operand2 = evaluatePrefixExpression(tokens, ++index);
        if (token == "add")
            return operand1 + operand2;
        else if (token == "sub")
            return operand1 - operand2;
        else if (token == "muti")
            return operand1 * operand2;
        else if (token == "div")
            return operand1 / operand2;
    }
    else if (token == "neg") {
        int op = evaluatePrefixExpression(tokens, ++index);
        return op * (-1);
    }
    else if (token == "doubleMe") {
        int op = evaluatePrefixExpression(tokens, ++index);
        return op * op;
    }
    else {
        return stoi(token);
    }
}

int main()
{
    ifstream infile("question.txt");
    ofstream outfile("answer.txt");

    if (!infile.is_open()) {  //文件不能打开
        cerr << "infile open err" << endl;
        return 1;

    }
    if (!outfile.is_open()) {
        cerr << "outfile open err" << endl;
        return 1;
    }
    //按行读取infile文件
    string line;

    while (getline(infile, line)) //只要有数据
    {
        int index = 0;
        vector<string> tokens = splitString(line);
        int t = evaluatePrefixExpression(tokens, index);
        for (const auto& token : tokens) {
            outfile << token << " ";
        }
        outfile << "=" << t << endl;
    }
    infile.close();
    outfile.close();
}

这是我的代码
question文件

img

answer文件

img

为什么会这样的啊,该怎么样修改呢

你的vector的下标超范围了

点击窗口的重试,你就看到它的问题在哪里了,然后看调用堆栈一个一个反推