fork download
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. #include <climits>
  5. using namespace std;
  6.  
  7. void doOp(const char & e, stack <int>& myS)
  8. {
  9. if (myS.size() == 2)
  10. {
  11. cout << "Performing "<<e<<endl;
  12. int num1, num2, answ;
  13. num2 = myS.top();
  14. myS.pop();
  15. num1 = myS.top();
  16. myS.pop();
  17. if (e == '+')
  18. answ = num1 + num2;
  19. else if (e == '-')
  20. answ = num1 - num2;
  21. else if (e == '*')
  22. answ = num1 * num2;
  23. else if (e == '/')
  24. answ = num1 / num2;
  25. else if (e == '%')
  26. answ = num1 % num2;
  27. else
  28. cout << "\nError- Invalid operator" << endl;
  29.  
  30. cout << "\nCalculating..." << endl << answ << endl;
  31. myS.push(answ);
  32. }
  33. else
  34. cout << "\nInvalid stack size- too few, or too many" << endl;
  35. }
  36.  
  37. int main() {
  38. stack <int> calcStack;
  39. string exp;
  40. char ans;
  41. cout << "\nDo you want to use the calculator?" << endl;
  42. cin >> ans;
  43. while (ans == 'y' && cin)
  44. {
  45. cin.ignore (INT_MAX, '\n');
  46. cout << "\nEnter your exp" << endl;
  47. getline (cin, exp);
  48. cout<< "Parsing: "<<exp<<endl;
  49. for (int i = 0; i < exp.size(); i++)
  50. {
  51. if (isspace(exp[i]))
  52. {
  53.  
  54. }
  55. else if (isdigit(exp[i]))
  56. {
  57. int num = exp[i] - '0';
  58. calcStack.push(num);
  59. cout << "Pushed " << num<<endl;
  60. }
  61. else
  62. doOp(exp[i], calcStack);
  63. }
  64.  
  65. while (!calcStack.empty())
  66. {
  67. calcStack.pop();
  68. }
  69.  
  70. cout << "\nDo you want to use the calculator again?" << endl;
  71. cin >> ans;
  72. }
  73.  
  74. return 0;
  75. }
  76.  
Success #stdin #stdout 0s 3424KB
stdin
y
54+2*
y
54+2z
stdout
Do you want to use the calculator?

Enter your exp
Parsing: 54+2*
Pushed 5
Pushed 4
Performing +

Calculating...
9
Pushed 2
Performing *

Calculating...
18

Do you want to use the calculator again?

Enter your exp
Parsing: 54+2z
Pushed 5
Pushed 4
Performing +

Calculating...
9
Pushed 2
Performing z

Error- Invalid operator

Calculating...
-1216617139

Do you want to use the calculator again?