example4_calculator.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <stack>
#include <string>
#include <sstream>

int evaluatePostfix(const std::string& expression) {
    std::stack<int> stack;
    std::istringstream iss(expression);
    std::string token;

    while (iss >> token) {
        if (isdigit(token[0])) {
            stack.push(std::stoi(token));
        } else {
            int operand2 = stack.top(); stack.pop();
            int operand1 = stack.top(); stack.pop();
            
            switch (token[0]) {
                case '+': stack.push(operand1 + operand2); break;
                case '-': stack.push(operand1 - operand2); break;
                case '*': stack.push(operand1 * operand2); break;
                case '/': stack.push(operand1 / operand2); break;
            }
        }
    }

    return stack.top();
}

int main() {
    std::string expression = "5 3 + 2 * 4 -";
    std::cout << "Postfix expression: " << expression << std::endl;
    std::cout << "Result: " << evaluatePostfix(expression) << std::endl;

    return 0;
}
Back to stack