Welcome to the Linux Foundation Forum!

Runtime error in my code...

INFIX TO POSTFIX CONVERSION :



#include

#include

#include

using namespace std;

char ifx[50],pfx[50],stk[50];

int top=-1,n;

void push(char ch)

{

if(top!=n-1)

{

top++;

stk[top]=ch;

}

else

cout<<"\nThe stack is full.";<br />
}

char pop()

{

char rmv;

if(top!=-1)

{

rmv=stk[top];

top--;

return rmv;

}

else

return '#';

}

char topele()

{

char ch;

if(top==-1)

{

ch='#';

return ch;

}

else

ch=stk[top];

}

int chkpres(char ch)

{

ch=topele();

switch(ch)

{

case '^':return 7;

break;

case '/':return 6;

break;

case '*':return 5;

break;

case '+':return 4;

break;

case '-':return 3;

break;

default:return 0;

break;

}

}

/*int braces(char *s)

{

int lftbr,rgtbr=0;

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

{

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

lftbr++;

else

rgtbr++;

}

if(lftbr==rgtbr)

return 0;

else if(lftbr
return 1;

else return -1;

}*/

int main()

{

char ele,elem,chk,popp,topp;

int pre,pres;

cout<<"\nEnter how many elements you want to enter in the infix expression: ";<br />
cin>>n;

cout<<"\nEnter the infix expression: ";<br />
for(int i=0;i
cin>>ifx[i];

topp=topele();

strcpy(pfx," ");

for(int i=0,j=0;ifx[i]!='\0',pfx[j]!='\0';++i,++j)

{

ele=ifx[i];

if(ele!='^' && ele!='*' && ele!='/' && ele!='+' && ele!='-')

pfx[j++]=ifx[i];

else if(ele=='^'||ele=='*'||ele=='/'||ele=='+'||ele=='-')

{

if(topp=='^'||topp=='*'||topp=='/'||topp=='+'||topp=='-')

{

pre=chkpres(ele);

pres=chkpres(topp);

if(pre>pres)

{

push(pre);

top++;

}

else if(pre<=pres)<br />
pfx[j++]=pres;

}

else

{

push(ele);

topp=ele;

}

}

else if(ele=='(')

{

i++;

}

else if(ele==')')

{

while(topp!='#')

{

popp=topp;

pfx[i]=popp;

}

}

cout<<"---------------"<<pfx[j++];<br />
}

cout<<"\nThe postfix expression is: ";<br />
for(int i=0;pfx[i]!='\0';++i)

{

cout<<pfx[i];<br />
}

cout<<endl;<br />
return 0;

}

Comments

  • marc
    marc Posts: 647
    I refuse to even read this code. No indentation, no comments nor explanations of any kind... I mean: come on!
  • mfillpot
    mfillpot Posts: 2,177
    marc wrote:
    I refuse to even read this code. No indentation, no comments nor explanations of any kind... I mean: come on!

    I agree, it would be best if you paste the indented code into pastbin.com and give a link here to the pastebin entry.

Categories

Upcoming Training