2016-12-20 103 views
0

我的程序基本上將中綴表達式轉換爲後綴表達式,儘管到目前爲止我的程序只接受單個數字。無論如何,當我嘗試編譯時,在輸入我的中綴表達式之後,程序幾乎立即崩潰。我的代碼:字符串輸入後程序崩潰

#include <stdio.h> 
#include <ctype.h> 
#include <string.h> 
#include <stdlib.h> 
int priority(char x); // Determines priority of incoming operator. 
void push(char x); // Pushes element to stack. 
char pop(); // Pops element from stack. 

char stack[10]; 
int top = -1; 

int main() { 
char init[20]; 
printf("Enter an expression: "); 
fgets(init, 20, stdin); 
int x = 0, y, z = 0; 
static char result[20]; 
while (init[x++] != '\0') { 
    if (isalnum(init[x])) 
     result[z++] = init[x]; // Operand printed out immediately. 
    else if (init[x] == '(') 
     push(init[x]); // '(' character pushed. 
    else if (init[x] == ')') { 
     while ((y = pop()) != '(')// Popping elements from stack until reaching '(' 
      result[z++] = y; 
    } else if (init[x] == ' ') { 
     z++; 
    else { 
     while (priority(init[x]) <= priority(stack[top])) // If expression operator has higher precedence than stack operator, expression operator is pushed onto stack. Else stack operator is popped and printed out. 
      result[z++] = pop(); 
     push(init[x]); 
    } 
} 
while (top != -1) 
    result[z++] = pop(); // Remaining operators printed out. 
printf("Final expression is %s.\n", result); 
} 
int priority(char x) { 
    int precedence = 0; 
    if(x == '(') 
     precedence = 0; 
    if(x == '+' || x == '-') 
     precedence = 1; 
    if(x == '*' || x == '/') 
     precedence = 2; 
    if(x == '^') 
     precedence = 3; 
    return precedence; 
} 

void push(char x) { 
stack[++top] = x; 
} 

char pop() { 
return stack[top--]; 
} 

我有這個工作的版本,但是當我看着這個版本,沒有什麼似乎有任何不同。有人能告訴我我錯過了什麼嗎?

+2

您的第一個循環(通過'init')包含一個非常糟糕的(我認爲)邏輯錯誤,並且您可以在其中無意中使用字符串終結符。嘗試將其改爲「for」循環。 –

+0

另外,你彈出'result'的第二個循環也有缺陷,並且會使用未被堆棧使用的'stack [0]'。談到堆棧,沒有堆棧溢出檢查。 –

回答

1

,我發現的主要問題是:

while (init[x++] != '\0') 當你在循環的條件檢查增加x的值,你再嘗試訪問它的調用函數:

isalnum(init[x])

第一個數字從來不以這種方式進行評估。所以如果你輸入「5 + 2」,只會評估「+2」,這是一個無效的中綴表達式。

+0

我確定的這個程序的最後一個版本是以同樣的方式完成的,它設法評估。只有在這裏,我的程序拒絕超過字符串輸入,並創建一個新的字符串,然後打印出來。我一直在學習C一段時間,這一切仍然讓我感到困惑,所以如果對這個問題有適當的解決方案會有所幫助。 –

+0

如果是這樣的話,你應該發佈你以前的版本以及@AmirulUmar – Amita