私のプログラムは基本的には中置式を後置式に変換しますが、これまでのところ私のプログラムは1桁の数字しか受け付けませんでした。とにかく、私の中置式を入力した直後にコンパイルしようとすると、プログラムはすぐにクラッシュします。私のコード:文字列入力後にプログラムがクラッシュする
#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'にポップアップする2番目のループも欠陥があり、スタックで使われていない' stack [0] 'を使います。スタックについて言えば、スタックオーバーフローチェックはありません。 –