fork(4) download
  1. #include <iostream>
  2. #include <stack>
  3.  
  4. typedef std::stack<int> stack_type;
  5.  
  6. stack_type get_values(std::istream&);
  7. int evaluate(stack_type&, std::istream&);
  8.  
  9. int main()
  10. {
  11. std::cout << "Enter your postfix expression:\n> ";
  12. stack_type s = get_values(std::cin); // leaves the operation tokens in the input stream.
  13. std::cout << evaluate(s, std::cin) << '\n';
  14. }
  15.  
  16. int evaluate(stack_type& s, std::istream& op_stream)
  17. {
  18. while (s.size() > 1)
  19. {
  20. int a = s.top();
  21. s.pop();
  22.  
  23. int b = s.top();
  24. s.pop();
  25.  
  26. char op;
  27. op_stream >> op;
  28.  
  29. int result;
  30. switch (op)
  31. {
  32. case '+': result = a + b; break;
  33. }
  34.  
  35. s.push(result);
  36. }
  37.  
  38. return s.top();
  39. }
  40.  
  41. stack_type get_values(std::istream& val_stream)
  42. {
  43. stack_type stack;
  44.  
  45. for (unsigned i=0; i<3; ++i)
  46. {
  47. int value ;
  48. val_stream >> value ;
  49. stack.push(value) ;
  50. }
  51.  
  52. return stack;
  53. }
  54.  
Success #stdin #stdout 0s 3436KB
stdin
1 2 3 + +
stdout
Enter your postfix expression:
> 6