[英]Infix to postfix Looping
在此处输入代码,
#include <stdio.h>
#include <ctype.h>
#define SIZE 50
char s[SIZE];
int top=-1;
void push(char elem)
{
s[++top]=elem;
}
char pop()
{
return(s[top--]);
}
int pr(char elem)
{
switch(elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/': return 3;
}
}
void main()
{
char infx[50],pofx[50],ch,elem;
int i=0,k=0,j;
for(j=0;j<=3;j++)
{
printf("\n\nRead the Infix Expression ? ");
scanf("%s",infx);
push('#');
while( (ch=infx[i++]) != '\0')
{
if( ch == '(')
push(ch);
else
if(isalnum(ch))
pofx[k++]=ch;
else
if( ch == ')')
{
while( s[top] != '(')
pofx[k++]=pop();
elem=pop();
}
else
{
while( pr(s[top]) >= pr(ch) )
pofx[k++]=pop();
push(ch);
}
}
while( s[top] != '#')
pofx[k++]=pop();
pofx[k]='\0';
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n",infx,pofx);
}
}
当循环中缀到后修复表达式时,它不会循环超过第一个循环。
它正在生成第一个循环的输出并显示其余循环的分段错误
请问有人可以指导我吗?
考虑一个例子
给定输入,
给定中缀扩展:a+b 后缀扩展:ab+
阅读中缀表达式? AB
分段错误(核心转储)
您需要为每个新输入重置pofx
和infx
的索引。 即在for-loop
重置i
和k
。 修复如下,
void main()
{
char infx[50],pofx[50],ch,elem;
int i=0,k=0,j;
for(j=0;j<=3;j++)
{
i=0;j=0;//here is the update
//rest of your code follows,
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.