wsh_wshkk 2023-07-01 11:06 采纳率: 70%
浏览 21
已结题

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

代码不能运行,报错

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

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

  • 写回答

3条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2023-07-01 14:18
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 10月27日
  • 已采纳回答 10月19日
  • 创建了问题 7月1日