Advertisement
Spocoman

3. Simple Calculator

Jan 10th, 2024
731
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <queue>
  4. #include <sstream>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9.     string line, s;
  10.     getline(cin, line);
  11.  
  12.     istringstream ss(line);
  13.  
  14.     queue<int> numbers;
  15.     queue<string> expressions;
  16.     int counter = 0;
  17.  
  18.     while (ss >> s) {
  19.         if (counter % 2 == 0) {
  20.             numbers.push(stoi(s));
  21.         }
  22.         else {
  23.             expressions.push(s);
  24.         }
  25.         counter++;
  26.     }
  27.  
  28.     int sum = numbers.front();
  29.     numbers.pop();
  30.  
  31.     while (!expressions.empty()) {
  32.  
  33.         if (expressions.front() == "+") {
  34.             sum += numbers.front();
  35.         }
  36.         else {
  37.             sum -= numbers.front();
  38.         }
  39.  
  40.         expressions.pop();
  41.         numbers.pop();
  42.     }
  43.  
  44.     while (!numbers.empty()) {
  45.         sum += numbers.front();
  46.         numbers.pop();
  47.     }
  48.  
  49.     cout << sum << endl;
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement