2017-07-12 115 views
0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <ctype.h> 
#define max 10 
void eval(char []); 
struct stack 
{ 
    int top; 
    int info[max]; 
}; 
int main() 
{ 
    char inf[20]; 
    printf("\n Enter the string "); 
    scanf("%s",inf); 
    printf("%s",inf); 
    eval(inf); 
    return 0; 
} 
void eval(char inf[]) 
{ 
    struct stack s; s.top=-1; 
    int instack(char); 
    int incoming(char); 
    void push(struct stack *, char); 
    char pop(struct stack *); 
    int i,j=0,ip,is,k; 
    char pst[20],ch,x; 
    for(i=0;i<strlen(inf);i++) 
    { 
     ch=inf[i]; 
     if(isdigit(ch)) 
     { 
      pst[j]=ch; 
      j++; 
     } 
     else if(ch==')') 
     { 
      while(x=pop(&s)!='(') 
      { 
       pst[j]=x; j++; 
      } 
     } 
     else if(s.top==-1) 
     { 
       push(&s,ch); 
     } 
     else 
     { 
       ip=incoming(ch); 
       is=instack(s.top); 
       if(ip>is) 
       { 
        push(&s,ch); 
       } 
       else 
       { 
       while((incoming(k=pop(&s))<(instack(s.top)))) 
       { 
        pst[j]=pop(&s); 
        j++; 
       } 
       push(&s,ch); 
       } 
     } 
    } 
    while(s.top!=-1) 
    { 
     pst[j]=pop(&s); 
     j++; 
    } 
    pst[j]='\0'; 
    printf("\n%s",pst); 
} 
void push(struct stack *s,char ch) 
{ 
    s->top=s->top+1; 
    s->info[s->top]=ch; 
} 
char pop(struct stack *s) 
{ 
    char ch; 
    ch=s->info[s->top]; 
    s->top=s->top-1; 
    return ch; 
} 
int incoming(char ch) 
{ 
    switch(ch) 
    { 
     case '+': 
     case '-': return 1; break; 
     case '*': 
     case '/': return 2; break; 
     case '(': return 4; break; 
    } 
} 
int instack(char ch) 
{ 
    switch(ch) 
    { 
     case '+': 
     case '-': return 1;break; 
     case '*': 
     case '/': return 2; break; 
     case '(': return 0; break; 
    } 
} 

我得到的输出为i/p-(5 + 6)*(3-2)是56?32?(asterix) 。我在Linux机器上使用GCC编译器。输出包含?和?一个+和一个运算符的位置。简单的输入如5 + 6正在正确转换。我到达的输出是56+。只有支架输入正在做这些?出现。Unkown字符代替输入中的运算符,用于输入到Postfix转换

+0

您是否试过在调试器中逐行逐行执行代码?也许你应该花一些时间阅读Eric Lippert的[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –

+2

启用你的警告,那么你将(可能)意识到,'x = pop(&s)!='(''由于运算符的优先级没有达到你所期望的。 – Ctx

回答

0

一个很小的错误,while(x=pop(&s)!='(')更改为while((x=pop(&s)) !='(')。而现在,它提供了您期望的输出。 :)