Untitled

 avatar
unknown
plain_text
2 years ago
1.6 kB
4
Indexable
#include <iostream>
#include <stack>
#include <string>
#include <cmath> // For pow() function if needed

using namespace std;

bool isOperator(char ch) {
    return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}

int performOperation(char op, int operand1, int operand2) {
    switch (op) {
        case '+': return operand1 + operand2;
        case '-': return operand1 - operand2;
        case '*': return operand1 * operand2;
        case '/': return operand1 / operand2;
        // Add more operators as needed
        // For exponentiation, you can use 'pow(operand1, operand2)'
        default: return 0; // Invalid operator
    }
}

int evaluatePostfixExpression(string postfix) {
    stack<int> st;
    int length = postfix.length();

    for (int i = 0; i < length; i++) {
        char ch = postfix[i];
        if (isdigit(ch)) {
            st.push(ch - '0'); // Convert char to int and push into stack
        } else if (isOperator(ch)) {
            // Evaluate the operator using the top two operands from the stack
            int operand2 = st.top();
            st.pop();
            int operand1 = st.top();
            st.pop();
            int result = performOperation(ch, operand1, operand2);
            st.push(result);
        }
    }

    // The result will be left at the top of the stack
    return st.top();
}

int main() {
    string postfixExpression;
    cout << "Enter the postfix expression: ";
    getline(cin, postfixExpression);

    int result = evaluatePostfixExpression(postfixExpression);
    cout << "Result: " << result << endl;

    return 0;
}
Editor is loading...