vencinachev

Hw2-Expression

Mar 13th, 2021 (edited)
282
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 <cmath>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7.  
  8. bool isOperation(char sym)
  9. {
  10.     return sym == '+' || sym == '-' || sym == '*' || sym == '/' || sym == '%';
  11. }
  12.  
  13. int main()
  14. {
  15.     int result, cntDigit = 0, num = 0;
  16.     vector<int> numbers;
  17.     vector<char> operations;
  18.     string expr;
  19.  
  20.     cout << "Enter expression: ";
  21.     getline(cin, expr);
  22.  
  23.     for (int i = expr.length() - 1; i >= 0; i--)
  24.     {
  25.  
  26.         if (isdigit(expr[i]))
  27.         {
  28.             num += (int)(expr[i] - '0') * pow(10, cntDigit);
  29.             cntDigit++;
  30.         }
  31.         else if (isOperation(expr[i]))
  32.         {
  33.             operations.insert(operations.begin(), expr[i]);
  34.             numbers.insert(numbers.begin(), num);
  35.             cntDigit = 0;
  36.             num = 0;
  37.         }
  38.     }
  39.     numbers.insert(numbers.begin(), num);
  40.  
  41.     result = numbers.at(0);
  42.     for (int i = 0; i < operations.size(); i++)
  43.     {
  44.         switch (operations.at(i))
  45.         {
  46.             case '+': result += numbers.at(i+1); break;
  47.             case '-': result -= numbers.at(i+1); break;
  48.             case '*': result *= numbers.at(i+1); break;
  49.             case '/': result /= numbers.at(i+1); break;
  50.             case '%': result %= numbers.at(i+1); break;
  51.         }
  52.     }
  53.  
  54.     cout << expr << result << endl;
  55.     return 0;
  56. }
  57.  
Add Comment
Please, Sign In to add comment