-1

I'm a writing a C++ program to Evaluate a PostFIx expression. This is the following code:

#include <iostream>
#include <string>
#include <stack>
#include <conio.h>

using namespace std;

int operand1;
int operand2;

bool operator_test(char character){ //to test whether its an operator or not
    if(character=='+' || character=='-' || character=='*' || character=='/')
        return true;
    else
        return false;
}

bool operand_test(char character){ //to test whether its an operand or not
    if(!operator_test(character) && character!='(' && character!=')')
            return true;
    else
        return false;
}

int DoOperation(char operation,int operand1,int operand2){
    if(operation=='+') return operand1+operand2;
    else if(operation=='-') return operand1-operand2;
    else if(operation=='*') return operand1*operand2;
    else if(operation=='/') return operand1/operand2;
}


int main(){
    string expression;
    cout<<"ENTER POSTFIX EXPRESSION"<<endl;
    cin>>expression;
    stack<int>test_stack;
    int result;
    for(int i=0;i<expression.length();i++){

        if(operand_test(expression[i]))
            test_stack.push(expression[i]);
        else if(operator_test(expression[i]))
            operand2=test_stack.top();

        test_stack.pop();
        operand1=test_stack.top();
        test_stack.pop();
        result=DoOperation(expression[i],operand1,operand2);
        test_stack.push(result);
    }

    cout<<"EVALUATION: "<<test_stack.top()<<endl;
    getch();
    return 0;
}

If I enter 23+ it should give 5 as output. But it's giving 51. What am I doing wrong here?? thanks in advance

Alex Shroyer
  • 3,499
  • 2
  • 28
  • 54
user3451638
  • 9
  • 1
  • 1
  • 1
    -1. Please write a sensible introduction and format the code properly (indentation). Try to make it easy for people to help you, not hard. – Christian Aichinger Mar 23 '14 at 07:51
  • You need to look up 'recursive descent expression parser' or the Dijkstra Shunting-yard algorithm. You will never ever never get there starting from here. – user207421 Mar 23 '14 at 08:54

1 Answers1

0

Of the top of my head, your code is lacking in several departments:

As @ChristianAichinger already pointed out, its formatting is horrible. This is a defect, since neither you nor anyone else will be able to read it.

Your else if does not open a block and therefore only operates on the next statement, which is operand2=test_stack.top(); and not the whole part that follows it. This would have been more obvious with proper formatting.

There is no part in your code that parses integers. Therefore, your code is missing a major part of its functionality.

More errors may exist, but analysis is fairly hard as long the code is in such a state.

danielschemmel
  • 10,885
  • 1
  • 36
  • 58