Guest User

Untitled

a guest
Apr 23rd, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. /*
  2. Evaluation Of postfix Expression in C++
  3. Input Postfix expression must be in a desired format.
  4. Operands must be integers and there should be space in between two operands.
  5. operands only have one num number.It's not fit like: 23 45*
  6. Only '+' , '-' , '*' and '/' operators are expected.
  7. */
  8. /**pseudo code
  9. * Evaluatepostfix(exp)
  10. * {
  11. * create a stack S
  12. * for i =0 to legth(exp)-1
  13. * {
  14. * if(exp[i] is operand)
  15. * s.push(exp[i])
  16. * else if(exp[i] is operator)
  17. * {
  18. * op1 =top()
  19. * pop()
  20. * op2 = top()
  21. * pop()
  22. * result <--perform(exp[i],op1,op2)
  23. * push(res)
  24. * }
  25. *
  26. *
  27. * }
  28. *
  29. * }
  30. *
  31. */
  32. #include <iostream>
  33. #include <stack>
  34. #include<queue>
  35. using namespace std;
  36.  
  37. // Function to evaluate Postfix expression and return output
  38. int EvauatePostfix(string expression)
  39. {
  40. // Declaring a Stack from Standard template library in C++.
  41. stack<int> stack1;
  42. int temp, operand1, operand2;
  43. for (int i = 0; i < expression.size(); i++) {
  44.  
  45. // Scanning each character from left.
  46. // If character is a delimitter, move on.
  47. if (expression[i] == ' ' || expression[i] == ',')
  48. continue;
  49.  
  50.  
  51. else if (expression[i] >= '0' && expression[i] <= '9') {
  52. stack1.push(expression[i] - '0');
  53. }
  54.  
  55. // If character is operator, pop two elements from stack,
  56. // perform operation and push the result back.
  57. else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') {
  58. operand2 = stack1.top();
  59. stack1.pop();
  60. operand1 = stack1.top();
  61. stack1.pop();
  62. switch (expression[i]) {
  63. case '+':temp = operand1 + operand2;
  64. stack1.push(temp);
  65. break;
  66. case '-':temp = operand1 - operand2;
  67. stack1.push(temp);
  68. break;
  69. case '*':temp = operand1 * operand2;
  70. stack1.push(temp);
  71. break;
  72. case '/':temp = operand1 / operand2;
  73. stack1.push(temp);
  74. break;
  75. default:cout << "Unexpected Error \n";
  76. return -1;
  77.  
  78. }
  79. }
  80. else
  81. cout << "Unexpected Error \n";
  82. return -1;
  83.  
  84. }
  85. return temp;
  86. }
  87. int main()
  88. { //parse the postfix expressions
  89. //test string string string1 = "23*54*+9-";
  90. string expression;
  91. cout << "Enter Postfix Expression \n";
  92. getline(cin, expression);
  93. int result = EvauatePostfix(expression);
  94. cout << "Output=" << result << endl;
  95.  
  96. // std::cout << "Hello, World!" << std::endl;
  97. return 0;
  98. }
Add Comment
Please, Sign In to add comment