#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack *s)
{
s->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!s->base)
exit(0);
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
return OK;
}
int Push(SqStack *s,ElemType e)
{
if(s->top-s->base>=s->stacksize)
{
s->base=(ElemType *)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(ElemType));
if(!s->base)
exit(0);
}
*(s->top)=e;
s->top++;
return OK;
}
int Pop(SqStack *s,ElemType *e)
{
if(s->top==s->base)
{
return ERROR;
}
*e=*--(s->base);
return OK;
}
int Stacklen(SqStack s)
{
return (s.top-s.base);
}
int InitStack(SqStack *s);
int Push(SqStack *s,ElemType e);
int Pop(SqStack *s,ElemType *e);
int StackLen(SqStack s);
int main()
{
SqStack s;
char c,e;
InitStack(&s);
printf("请输入中缀表达式\n");
scanf("%c",&c);
while(c!="#")
{
while(c>="0"&&c<="9")
{
printf("%c",c);
scanf("%c",&c);
if(c<"0"||c>"9")
{
printf(" ");
}
}
if(")"==c)
{
Pop(&s,&e);
while("("!=e)
{
printf("%c",e);
Pop(&s,&e);
}
}
else if("+"==c||"-"==c)
{
if(!Stacklen(s))
{
Push(&s,c);
}
else
{
do
{
Pop(&s,&e);
if("("==e)
{
Push(&s,e);
}
else
{
printf("%c",e);
}
}while(Stacklen(s)&&"("!=e);
Push(&s,c);
}
}
else if("*"==c||"/"==c||"("==c)
{
Push(&s,c);
}
else if("#"==c)
{
break;
}
else
{
printf("用户输入失败\n");
return ERROR;
}
scanf("%c",&c);
}
while(Stacklen(s))
{
Pop(&s,&e);
printf("%c",e);
}
return 0;
}
这段程序哪里出错了,调试没有错,为什么运行的时候会出来一大堆警告呢?
解决方案
10
在每个最后不带\n的printf后面加fflush(stdout);
在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin);
另外请检查scanf的返回值。
在每个不想受接收缓冲区旧内容影响的scanf前面加rewind(stdin);
另外请检查scanf的返回值。
//请今后要用
int c;
scanf("%c",&c);
//时,都改为
char s[2];
int c;
scanf("%1s",s);
c=s[0];
20
Push函数中,假如relloc后,s->top可能已经失效,s->stacksize也会发生变化
10
你错误地使用了scanf(“%c”,&c);