You are using a version without Ads of this website. Please, consider donating:

### Evaluating postfix

Hello all I am stuck trying to write a program that reads in an expression, turns that expression into postfix, and then evaluates it. The program reads in the expression and converts it to postfix, but I cant get it to evaluate correctly. For example I input 2 + 3 postfix equals 23+ and it returns 1 as the answer. Any help would be greatly appreciated!

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113`` ``````#include #include #include #include #include using namespace std; int evaluate (int opn1, char token, int opn2) { int result; switch (token) { case '+' : result = opn1 + opn2; case '-' : result = opn1 - opn2; case '*' : result = opn1 * opn2; case '/' : result = opn1 / opn2; case '^' : result = opn1 ^ opn2; } return result; } int priority(char a) { int temp; if (a == '^') temp = 3; else if (a == '*' || a == '/') temp = 2; else if (a == '+' || a == '-') temp = 1; else if ( a == '(') temp = 0; return temp; } int main() { string aline; string st;; int result; int opn2, opn1, temp; stack ostack; stack istack; stringstream output2; stringstream output; getline(cin,aline); st = output.str(); for (int i = 0; i < aline.length(); i++) { if(aline[i] == ' ') i++; if (aline[i] == '+' || aline[i] == '-' || aline[i] == '*' || aline[i] == '/' || aline[i] == '^') { while (!ostack.empty() && priority(ostack.top()) >= priority(aline[i])) { output << ostack.top(); ostack.pop(); } ostack.push(aline[i]); } else if (aline[i] == '(') { ostack.push(aline[i]); } else if (aline[i] == ')') { while (ostack.top() != '(') { output << ostack.top(); ostack.pop(); } ostack.pop(); } else { output << aline[i]; } } while (!ostack.empty()) { output << ostack.top(); ostack.pop(); } cout<

Here is what it prints out:
2 + 3
2 + 3
23+
temp 2
temp 3
token +
opn2 3
opn1 2
result 1

I haven't managed to fix my postfix issues either, but I don't think you need to push both the result and st[i] at the end of your evaluation "for" loop.
Hi zeppelyn sorry I didn't see your comment. If you add breaks after each statement in evaluate this code should work for you.
Topic archived. No new replies allowed.