我的程序基本上將中綴表達式轉換爲後綴表達式,儘管到目前爲止我的程序只接受單個數字。無論如何,當我嘗試編譯時,在輸入我的中綴表達式之後,程序幾乎立即崩潰。我的代碼:字符串輸入後程序崩潰
#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--];
}
我有這個工作的版本,但是當我看着這個版本,沒有什麼似乎有任何不同。有人能告訴我我錯過了什麼嗎?
您的第一個循環(通過'init')包含一個非常糟糕的(我認爲)邏輯錯誤,並且您可以在其中無意中使用字符串終結符。嘗試將其改爲「for」循環。 –
另外,你彈出'result'的第二個循環也有缺陷,並且會使用未被堆棧使用的'stack [0]'。談到堆棧,沒有堆棧溢出檢查。 –