我的程序基本上将中缀表达式转换为后缀表达式,尽管到目前为止我的程序只接受单个数字。无论如何,当我尝试编译时,在输入我的中缀表达式之后,程序几乎立即崩溃。我的代码:字符串输入后程序崩溃
#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]'。谈到堆栈,没有堆栈溢出检查。 –