简体   繁体   English

中缀到后缀循环

[英]Infix to postfix Looping

enter code here,在此处输入代码,

#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);
    }
}

When looping through infix to post fix expression,it's not looping beyond 1st loop.当循环中缀到后修复表达式时,它不会循环超过第一个循环。

It is producing output of 1st loop and showing segmentation fault for rest of loops它正在生成第一个循环的输出并显示其余循环的分段错误

Please can somebody guide me?请问有人可以指导我吗?

Consider an example考虑一个例子

given input,给定输入,

Given Infix Expn: a+b Postfix Expn: ab+给定中缀扩展:a+b 后缀扩展:ab+

Read the Infix Expression ?阅读中缀表达式? ab AB
Segmentation fault (core dumped)分段错误(核心转储)

you need to reset the index for pofx and infx for every new input.您需要为每个新输入重置pofxinfx的索引。 ie to reset i and k in the for-loop .即在for-loop重置ik Fix as below,修复如下,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM