#include <iostream>
#include <stack>
#include <string>
#include <cctype>
#include <sstream>
using namespace std;
// Function to check if the character is an operator
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
// Function to get the precedence of the operators
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
string infixToPostfix(const string& infix) {
stack<char> operators;
string postfix;
for (char c : infix) {
if (isalnum(c)) { // If the character is an operand (single character)
postfix += c; // Add operand to postfix expression
} else if (isOperator(c)) { // If the character is an operator
while (!operators.empty() && precedence(operators.top()) >= precedence(c)) {
postfix += ' '; // Add space for separation
postfix += operators.top();
operators.pop();
}
postfix += ' '; // Add space for separation
operators.push(c);
// Pop all the operators from the stack
while (!operators.empty()) {
postfix += ' '; // Add space for separation
postfix += operators.top();
operators.pop();
return postfix;
// Function to evaluate postfix expression
int evaluatePostfix(const string& postfix) {
stack<int> operands;
istringstream iss(postfix);
string token;
while (iss >> token) { // Read each token separated by spaces
if (isalnum(token[0])) { // If the token is an operand
operands.push(token[0] - '0'); // Assuming single digit operands (0-9)
} else if (isOperator(token[0])) { // If the token is an operator
int right = operands.top(); operands.pop();
int left = operands.top(); operands.pop();
switch (token[0]) {
case '+': operands.push(left + right); break;
case '-': operands.push(left - right); break;
case '*': operands.push(left * right); break;
case '/': operands.push(left / right); break;
}
return operands.top(); // The result is the top element of the stack
int main() {
string infix;
cout << "Enter an infix expression (single characters, use spaces for separation): ";
getline(cin, infix);
string postfix = infixToPostfix(infix);
cout << "Postfix expression: " << postfix << endl;
int result = evaluatePostfix(postfix);
cout << "Evaluation of postfix expression: " << result << endl;
return 0;