这样子用栈有什么问题嘛?
咋没办法实现进栈呢?
#include
#include
#define MAXSIZE 100
typedef struct
{
int data[MAXSIZE];
int top;
}stack;
void push(stack S,int z)
{
S.data[S.top]=z;
S.top++;
return;
}
int pop(stack S)
{
return S.data[--S.top];
}
int main()
{
stack S;
S.top=0;
char bds[20][5]={0};
char a[5]={0};
int n=0;
int x,y;
for(int i=0;;i++)
{
scanf("%s",&a);
if(a[0]=='#')
break;
else
{
strcpy(bds[i],a);
n++;
}
}
for(int i=0;iif(bds[i][0]!='+'&&bds[i][0]!='-'&&bds[i][0]!='*'&&bds[i][0]!='/')
{
int k=0;
if(strlen(bds[i])=='1')
k=bds[i][0]-'0';
else
{
if(bds[i][0]=='-')
{
for(int j=1;j<strlen(bds[i]);j++)
k=k*10+(bds[i][j]-'0');
}
else
{
for(int j=0;j<strlen(bds[i]);j++)
k=k*10+(bds[i][j]-'0');
}
}
push(S,k);
}
else
{
x=pop(S);
if(S.top==0)
{
printf("Expression Error:%d",x);
break;
}
else
{
y=pop(S);
switch(bds[i][0])
{
case '+':push(S,x+y);
case '-':push(S,x-y);
case '*':push(S,x*y);
case '/':
{
if(y==0)
printf("Error:%d/0",x);
else push(S,x/y);
}
}
}
}
}
if(S.top==1)
printf("%d",S.data[0]);
else printf("Expression Error:%d",S.data[S.top-1]);
return 0;
}
scanf("%s", &a); scanf忽略空白字符,输入1 2 +,a的值只有1,后面的舍弃了。
问题太多,根据你的改写了下。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXSIZE 100
typedef struct
{
int data[MAXSIZE];
int top;
} stack;
void push(stack *S, int z) //修改参数的值需要传指针
{
if (S->top >= MAXSIZE)
return;
S->data[S->top] = z;
S->top++;
// return;
}
int pop(stack *S)
{
if (S->top <= 0)
return 0;
int x = S->data[--S->top];
S->data[S->top] = 0;
return x;
}
int main()
{
char bds[20][MAXSIZE] = {0};
int n = 0;
for (int i = 0;; i++, n++)
{
// scanf("%s", &a);//scanf不接收空白字符,一次读取不了一行
fgets(bds[n], MAXSIZE, stdin);
if (bds[n][0] == '#') //
break;
}
for (int i = 0; i < n; i++)
{
stack S = {0};
int len = strlen(bds[i]) - 1; // fgets会接受末尾的'\n'
int k = 0, flag = 1, err = 0;
int x, y;
for (int j = 0; j < len; j++)
{
if (isspace(bds[i][j])) //跳过空白字符
continue;
if (isdigit(bds[i][j]) || (bds[i][j] == '-' && isdigit(bds[i][j + 1])))
{
if (bds[i][j] == '-')
{
flag = -1;
continue;
}
for (; j < len; j++)
{
if (isdigit(bds[i][j]))
k = k * 10 + (bds[i][j] - '0');
else
{
k *= flag;
flag = 1;
j--;
break;
}
}
push(&S, k);
k = 0;
}
else
{
y = pop(&S);
if (S.top == -1)
{
printf("Expression Error:%d\n", y); //
err = 1;
break;
}
x = pop(&S);
switch (bds[i][j])
{
case '+':
push(&S, x + y);
break; //
case '-':
push(&S, x - y);
break; //
case '*':
push(&S, x * y);
break; //
case '/':
{
if (y == 0)
{
printf("Error:%d\n", x); //
err = 1;
}
else
push(&S, x / y);
break; //
}
}
}
}
if (!err) //出错则不显示下面信息
{
if (S.top == 1)
printf("%d\n", S.data[0]);
else
printf("Expression ErrorB:%d\n", S.data[S.top - 1]); //
}
err = 0;
}
return 0;
}