Ogbonnaya-Jr/String Post-fix expression to String Infix expression

//This is the header file to find infix expression for
// a given postfix expression.
#include <iostream>
#include <stack>
#include <cstdlib>
#include <bits/stdc++.h>
using namespace std;
// return true if the char is between A-Z or a-z
// or else returns false
bool isNotOperator(char ch)
{
return (ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z');
}
// Getting Infix Expression when we already have a given postfix
// expression
string getInfixExpression(string expression)
{
stack<string> s;
for (int i=0; i < expression[i]; i++)
{
cout << "i: " << i << "\n";
// check if char is not an operator
if (isNotOperator(expression[i]))
{
cout << "isNotOperator" << "\n";
// translate into a string
string oper(1, expression[i]);
// push onto stack
s.push(oper);
}
// it is an operator
else
{
// get the top two variables
string oper1 = s.top();
cout << "oper1: " << oper1 << "\n";
s.pop();
string oper2 = s.top();
cout << "oper2: " << oper2 << "\n";
s.pop();
// put back onto stack with correct parenthesis and operator
// this makes the top item on the stack become a longer and longer string
s.push("(" + oper2 + expression[i] +
oper1 + ")");
}
}
// return the complete infix expression
return s.top();
}
int main() {
string expression = "jklm*+*n/";
// call the function and print out the result
cout << getInfixExpression(expression);
return 0;
}

Comments

Popular posts from this blog