#include <iostream>
#include<string>
#include <assert.h>
#include<cctype>
#include<stack>
std::string postfix(std::string exp);
int main(){
std::string infixExp;
std::cout<<"NOTE: Enter # for infix expression to stop. \n";
while (true)
{
std::cout<<"\nInfix expression? ";
getline(std::cin,infixExp);
if (infixExp=="#") break;
std::cout<<"Postfix expression is "<<postfix(infixExp)<<std::endl;
}
}
std::string postfix(std::string exp){
char token, topToken;
std::stack<int> opStack;
std::string postfixExp;
const std::string BLANK = " ";
for (int i = 0; i < exp.length(); i++)
{
token = exp[i];
switch (token)
{
case ' ': break;
case '(': opStack.push(token); break;
case ')':
for (;;)
{
assert(!opStack.empty());
topToken = opStack.top();
opStack.pop();
if(topToken == '(') break;
postfixExp.append(BLANK + topToken);
}
break;
case '+':
case '-':
case '*':
case '/':
case '%':
for(;;){
if (opStack.empty() ||
opStack.top() == '(' ||
(token=='*' || token=='/' || token=='%') &&
(opStack.top() == '+' || opStack.top() == '-'))
{
opStack.push(token);
break;
}
else
{
topToken = opStack.top();
opStack.pop();
postfixExp.append(BLANK + topToken);
}
}
break;
default:
postfixExp.append(BLANK + token);
for(;;){
if(!isalnum(exp[i+1])) break;
i++;
token = exp[i];
postfixExp.append(1,token);
}
}
}
for(;;){
if (opStack.empty()) break;
topToken = opStack.top();
opStack.pop();
if (topToken!='(')
{
postfixExp.append(BLANK + topToken);
}
else
{
std::cout<<"*** Error in infix expression ***\n";
break;
}
}
return postfixExp;
}