SabirSazzad

Postfix to Evaluation

Feb 26th, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include<iostream>
  2. #include<cctype>
  3. #include<stack>
  4. using namespace std;
  5.  
  6. int eval(int op1, int op2, char operate) {
  7.    switch (operate) {
  8.       case '*': return op2 * op1;
  9.       case '/': return op2 / op1;
  10.       case '+': return op2 + op1;
  11.       case '-': return op2 - op1;
  12.       default : return 0;
  13.    }
  14. }
  15.  
  16. int evalPostfix(char postfix[], int size) {
  17.    stack<int> s;
  18.    int i = 0;
  19.    char ch;
  20.    int val;
  21.    while (i < size) {
  22.       ch = postfix[i];
  23.       if (isdigit(ch)) {
  24.          s.push(ch-'0');
  25.       }
  26.       else {
  27.          int op1 = s.top();
  28.          s.pop();
  29.          int op2 = s.top();
  30.          s.pop();
  31.          val = eval(op1, op2, ch);
  32.          s.push(val);
  33.       }
  34.       i++;
  35.    }
  36.    return val;
  37. }
  38. int main() {
  39.    char postfix[] = {'5','6','8','+','*','2','/'};
  40.    int size = sizeof(postfix);
  41.    int val = evalPostfix(postfix, size);
  42.    cout<<"\nExpression evaluates to "<<val;
  43.    cout<<endl;
  44.    return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment