C ++ Postfix评估问题

时间:2018-06-27 01:42:22

标签: c++ c++11 postfix-notation

stack<int> s;
int main() {
    string exp;
    cout << "Enter postfix expression: ";
    getline(cin, exp);
    int calc = evaluatePosfix(exp);
    cout << calc << endl;
}

int evaluatePosfix(string exp) {
    for (int i = 0; i < exp.length(); i++) {
        if (exp[i] == ' ' || exp[i] == ',') {
            continue;
        }
        if (isNum(exp[i])){
            int operand = 0;
            while(i < exp.length() && isNum(exp[i])) {
                operand = (operand*10) + (exp[i] - '0');
                i++;
            }
            i--;
            cout << operand << "&&" << endl;
            s.push(operand);
        }

        else if(isOperator(exp[i])) {
            int operand2 = s.top(); s.pop();
            int operand1 = s.top(); s.pop();
            int result = performOperation(operand1, operand2, exp[i]);
            s.push(result);
        }

        //cout << s.top() << " $$$" << endl;
    }

    return s.top();
}

bool isOperator(char c) {
    if (c == '+' || c == '-' || c == '*' || c == '/') {
        return true;
    }
    return false;
}

bool isNum(char c) {
    if (c >= '0' || c <= '9') {
        return true;
    }
    return false;
}

int performOperation(int operand1, int operand2, char operation) {
    if (operation == '+') {
        return operand1 + operand2;
    }
    else if (operation == '-') {
        return operand1 + operand2;
    }
    else if (operation == '*') {
        return operand1 * operand2;
    }
    else if (operation == '/') {
        return operand1 / operand2;
    }
    else {
        cout << "Error" << endl;
        return -1;
    }
}

后缀未正确评估。当我输入22+时,它返回215而不是4。当程序检测到一个运算符时,它应该弹出堆栈中的2个元素,但是由于某种原因,它没有这样做。调用performOperation时,不会发生该操作,因此不会将任何内容压入堆栈。

2 个答案:

答案 0 :(得分:1)

如果假设<Rectangle>...的评估结果为22+,则此部分为罪魁祸首:

4

您编写的代码可以处理大于10的数字,但是您的示例建议您仅支持一位数字。

答案 1 :(得分:0)

@meat是正确的,您需要读取输入流(文件或cin)作为标记。

#include <cstring>
char token[6];

while (stream >> token)
{
    if (token[0] == '=') // what ever the end char is
    {
        //process and evaluate expression
    }
    else if (isdigit(*token)) // will pass a 4 byte int not just 0-9
    {
        // process a number
    }
    else if (ispunct(token0])) // is 1 byte math symbol + - * / 
    {
        // process a math symbol
    }

应该可以解决0-9阅读问题。