#include <iostream>
#include <stack>
#include <string>
int operatorLevel(char op) {
switch (op) {
case '+': case '-': return 1;
case '*': case '/': return 2;
default: return 0;
}
}
bool isOp(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
std::string convertToPostfix(const std::string& infix) {
std::stack<char> opStack;
std::string postfix;
for (char c : infix) {
if (isalnum(c)) {
postfix += c;
} else if (c == '(') {
opStack.push(c);
} else if (c == ')') {
while (!opStack.empty() && opStack.top() != '(') {
postfix += opStack.top();
opStack.pop();
}
opStack.pop();
} else if (isOp(c)) {
while (!opStack.empty() && operatorLevel(c) <= operatorLevel(opStack.top())) {
postfix += opStack.top();
opStack.pop();
}
opStack.push(c);
}
}
while (!opStack.empty()) {
postfix += opStack.top();
opStack.pop();
}
return postfix;
}
int main() {
std::string infixExpression;
std::cout << "Enter an infix expression: ";
std::cin >> infixExpression;
std::string postfixExpression = convertToPostfix(infixExpression);
std::cout << "The postfix expression is: " << postfixExpression << std::endl;
return 0;
}
To embed this program on your website, copy the following code and paste it into your website's HTML: