2014-02-24 37 views
-1

我想写一个从Infix转换为前缀的代码。这是它:C输出中显示的奇怪符号。任何线索?

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
int top = -1, size; 

int precedence(char c) 
{ 
    if (c=='+' || c=='-') 
     return 1; 
    if (c=='*' || c=='/') 
     return 2; 
     if (c=='^') 
     return 3; 
} 



/* push the given data into the stack */ 
void push(char *stack, char data) { 
    top++; 
    //printf("Top:%d, Size:%d\n",top,size); 
    if (top >= size) { 
     printf("Stack Overflow\n"); 
     return; 
    } 

    //printf("Hello in PUSH\n"); 
    stack[top] = data; 
    return; 
} 

/* pop the top element from the stack */ 
void pop(char *stack) { 
    if (top <= -1) { 
     printf("Stack Underflow!\n"); 
     return; 
    } 
    stack[top] = '*'; 
    top--; 
    return; 
} 
char peek(char *stack) 
{ 
    return stack[top]; 
} 
void stackp(char *stack) 
{ 
    int r; 
printf("Print Stack:\n"); 
for(r=0;r<top;r++) 
    printf("%c\n",stack[r]); 
} 


int main() 
{ 
    char data; 
    char ip[100]; 
    int i,j; 
    printf("Enter the Input, Input can be of max 100 characters:\n"); 
    scanf("%s", ip); 
    size=strlen(ip); 
    char op[size]; 
    char stack[size]; 
    for(i=size-1;i>-1;i--) 
    { 

     stackp(stack);// Print Stack 
     //printf("Hello\n"); 
      //printf("%c ",ip[i]);// Print current element 
      if((ip[i]-'0')>0 && (ip[i]-'0')<9) 
      { 
     // printf("Hello\n"); 
      strcat(op,&ip[i]); 
     printf("%s \n",op); 
      break; 
      } 
     else if(top==-1) 
      { 
       push(stack,ip[i]); 
       break; 
      } 
     else if(top!=-1 && ip[i]==')')// Brackets Condition 
     { 
      while(stack[top]!='(') 
       { 
        strcat(op,&ip[i]); 
        pop(stack); 
       } 

     } 
     else if(top!=-1 && (precedence(stack[top])-precedence(ip[i])>0)) 
     { 
      while(precedence(stack[top])-precedence(ip[i])>0 || top!=-1) 
      { 
       strcat(op,&ip[i]); 
       pop(stack); 
      } 
      push(stack,ip[i]); 
     } 
     else 
     { 
      push(stack,ip[i]); 
     } 

    } 
    //printf("%s ",op); 
} 

虽然我编译和运行。我在输出中获得了非常好的strange looking symbol

有人能告诉我到底是什么吗?我该如何纠正它?

+1

其非打印字符,可能ASCII 0之间的事情到40 – tesseract

+1

看起来像什么火狐将使用显示非打印字符U + 0001。通过不输出值为1的字节来纠正它。找出你的哪个输出语句发出它,然后找出为什么被打印的var不包含你期望它包含的东西 – ikegami

+1

tesseract意味着40个八进制,这是20十六进制,他的字面意思是“之间”,因为40个八进制是一个空间。 – ikegami

回答

0

代码追加到unitialiised变量以及与此引发未定义行为在这里:

char op[size]; 

    ... 

     strcat(op, ...); 

为了解决这个问题正确初始化op所有0 S,这样做:

char op[size]; 
    memset(op, 0, size); 

另外:precedence()错过任何值的情况下返回任何情况下都不满足。

添加最终return声明,像

int precedence(const char c) 
{ 
    ... 

    return 0; 
} 
+0

谢谢!我纠正了优先顺序()。我仍然不明白,当一个变量没有被初始化时它总是输出一些特殊字符,或者它只能用于字符串和字符? – user248884

+0

@ user248884:读取未初始化的变量会引发程序未定义的行为,所以实际上可能发生任何事情。 Striklty避免了程序的*未找到行为*。 – alk