Asked in C++ Programming
C++ Programming

What is a c plus plus program that accepts a mathematical expression from a user and converts it to postfix expression and evaluates the result?

Answer

Wiki User
09/28/2013

#include <iostream>

#include <cstdlib>

#include <cstring>

#include <cstdio>

#define size 400

using namespace std;

char infix[size]="\0",postfix[size]="\0",Stack[size];

int top;

int precedence(char ch)

{

switch(ch)

{

case '^':return 5;

case '/':return 4;

case '*':return 4;

case '+':return 3;

case '-':return 3;

default:return 0;

}

}

char Pop()

{

char ret;

if(top!=-1)

{

ret=Stack[top];

top--;

return ret;

}

else return '#';

}

char Topelem()

{

char ch;

if(top!=-1) ch=Stack[top];

else ch='#';

return ch;

}

void Push(char ch)

{

if(top!=size-1)

{

top++;

Stack[top]=ch;

}

}

int braces(char* s)

{

int l,r;

l=0;r=0;

for(int i=0;s[i];i++)

{

if(s[i]=='(') l++;

if(s[i]==')') r++;

}

if(l==r) return 0;

else if(l<r) return 1;

else return -1;

}

int main()

{

char ele,elem,st[2];

int T,prep,pre,popped,j=0,chk=0;

cin>>T;

while(T--)

{

j=0;chk=0;top=-1;

strcpy(postfix," ");

cin>>infix;

chk=braces(infix);

if(chk==0)

{

for(int i=0;infix[i];i++)

{

if(infix[i]=='(')

{

elem=infix[i];

Push(elem);

}

else if(infix[i]==')')

{

while((popped=Pop())!='(')

{

postfix[j++]=popped;

}

}

else if(infix[i]=='^'infix[i]=='/'infix[i]=='*'infix[i]=='+'infix[i]=='-')

{

elem=infix[i];

pre=precedence(elem);

ele=Topelem();

prep=precedence(ele);

if(pre>prep) Push(elem);

else

{

while(prep>=pre)

{

if(ele=='#') break;

popped=Pop();

ele=Topelem();

postfix[j++]=popped;

prep=precedence(ele);

}

Push(elem);

}

}

else

{

postfix[j++]=infix[i];

}

}

while((popped=Pop())!='#') postfix[j++]=popped;

postfix[j]='\0';

cout<<postfix;

}

}

}