2014-02-24 46 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