c-Postfix表达式-检查空格



因此,我试图在main函数中添加一个if语句,以检查是否存在一些空白。如果是这样的话,它将转到行中的下一个号码/操作员。例如,如果我要键入2 3 4 * +,我应该得到14。然而,当我运行代码时,我会得到一个随机数。当我在没有像234*+这样的空格的情况下这样做时,我会得到14。有人能告诉我我做错了什么,我该怎么解决吗?

#include <ctype.h>
#include <stdio.h>
#define MAX 20
typedef struct stack {
int data[MAX];
int top;
} stack;
int evaluate(char x, int op1, int op2) {
if (x == '+')
return (op1 + op2);
if (x == '-')
return (op1 - op2);
if (x == '*')
return (op1 * op2);
if (x == '/')
return (op1 / op2);
if (x == '%')
return (op1 % op2);
}
void init(stack *s) {
s->top = -1;
}
void push(stack *s, int x) {
s->top = s->top + 1;
s->data[s->top] = x;
}
int pop(stack *s) {
int x;
x = s->data[s->top];
s->top = s->top - 1;
return (x);
}
int main() {
stack s;
char x;
int op1, op2, val;
init(&s);
printf("Enter a Postfix Expression: ");
while ((x = getchar()) != 'n') {
if (isdigit(x))
push(&s, x - 48); //x-48 for removing the effect of ASCII
if (isspace(x))
continue;
else {
op2 = pop(&s);
op1 = pop(&s);
val = evaluate(x, op1, op2);
push(&s, val);
}
}
val = pop(&s);
printf("nValue of expression=%d",val);
return 0;
}

首先,char x需要替换为int xgetchar返回的值并不总是适合char。但这不是你问的问题。


如果字符是数字,则将其视为数字和运算符。这个

if(isdigit(x))
push(&s,x-48); //x-48 for removing the effect of ASCII
if (isspace(x))
continue;
else
{
op2=pop(&s);
op1=pop(&s);
val=evaluate(x,op1,op2);
push(&s,val);
}

应该是

if (isdigit(x)) {
push(&s, x-48);
}
else if (isspace(x)) {
continue;
}
else {
int op2 = pop(&s);
int op1 = pop(&s);
int val = evaluate(x, op1, op2);
push(&s, val);
}

或者只是

if (isdigit(x)) {
push(&s, x-48);
}
else if (!isspace(x)) {
int op2 = pop(&s);
int op1 = pop(&s);
int val = evaluate(x, op1, op2);
push(&s, val);
}

你不应该指望拖尾换行。所以你真的应该有以下内容:

while ( ( x = getchar() ) != EOF ) {
if (isspace(x))
continue;
if (isdigit(x)) {
push(&s, x-48);
} else {
int op2 = pop(&s);
int op1 = pop(&s);
int val = evaluate(x, op1, op2);
push(&s, val);
}
}

最后,您应该处理输入23++234+23!的人。

最新更新