Advertisement
Guest User

Untitled

a guest
Mar 4th, 2015
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. #include <list> /* Linked Lists */
  2. #include <stack> /* Stacks */
  3. #include <iostream> /* cout cin */
  4.  
  5.  
  6. int main() {
  7.  
  8. std::stack< double, std::list<double> > postfixStack;
  9. std::string input;
  10.  
  11. std::cout << "Enter a postfix expression: ";
  12.  
  13. std::getline(std::cin, input);
  14.  
  15. while (input != "") {
  16. std::cout << "Input expression: " << input << std::endl;
  17. for (int i = 0; i<input.length()-1; i++) {
  18. if (input.compare(i, 1, " ")) { // should ignore spaces, but doesn't
  19. std::cout << "Skipping element " << i << " n";
  20. } else if (static_cast<int>(input[i]) == input[i]) { // push numbers onto the stack
  21. postfixStack.push(static_cast<double>(input[i]));
  22. std::cout << "Pushing " << input[i] << " onto the stack.n";
  23. } else if (input.compare(i, 1, "+")) { // pop two numbers off the stack (1), apply the operator to them (2), and push that onto the stack (3)
  24. double operand1 = postfixStack.top();
  25. postfixStack.pop();
  26. double operand2 = postfixStack.top();
  27. postfixStack.pop();
  28. postfixStack.push(operand1 + operand2);
  29. std::cout << "Adding " << operand1 << " and " << operand2 << std::endl;
  30. }
  31. }
  32. std::getline(std::cin, input);
  33. }
  34.  
  35. if (!postfixStack.empty()) {
  36. std::cout << "Result of expression: " << postfixStack.top() << std::endl;
  37. } else {
  38. std::cout << "It appears that you did not enter an expression to evaluate.n";
  39. }
  40.  
  41. return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement