Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <iostream>
  2. #include <deque>
  3.  
  4. using namespace std;
  5.  
  6. deque<double> operands;
  7. deque<char> operators;
  8.  
  9. void filterInput(char input[])
  10. {
  11.     char ops[5] = { '+','-','*','/','=' };
  12.     for (char item : ops)
  13.     {
  14.         if (input[0] == item)
  15.         {
  16.             operators.push_back(input[0]);
  17.             return;
  18.         }
  19.     }
  20.  
  21.     operands.push_back(atof(input));
  22. }
  23.  
  24. double calculate()
  25. {
  26.     double result;
  27.     while (operators.size())
  28.     {
  29.         switch (operators.front())
  30.         {
  31.         case '+':
  32.             result = operands[0] + operands[1];
  33.             break;
  34.         case '-':
  35.             result = operands[0] - operands[1];
  36.             break;
  37.         case '*':
  38.             result = operands[0] * operands[1];
  39.             break;
  40.         case '/':
  41.             result = operands[0] / operands[1];
  42.             break;
  43.         default:
  44.             operators.pop_front();
  45.             break;
  46.         }
  47.  
  48.         //pop the 1st and 2nd elements from the que
  49.         operands.pop_front();
  50.         operands.pop_front();
  51.         //push in the result from the front
  52.         operands.push_front(result);
  53.  
  54.         //pop the operator
  55.         operators.pop_front();
  56.     }
  57.     return operands[0];
  58. }
  59.  
  60. int main()
  61. {
  62.     char buffer[50];
  63.     memset(buffer, 0, sizeof(buffer));
  64.  
  65.     while (!cin.eof()) //while CTRL+Z is not pressed
  66.     {
  67.         cin >> buffer;
  68.         filterInput(buffer);
  69.     }
  70.     operands.pop_back(); // ^Z would get pushed as 0 value, so we pop it out when we exit the loop
  71.     cout << "Result: " << calculate() << endl;
  72.     system("pause");
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement