2016-12-20 127 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