关于括号匹配检验的问题
#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 10
#define STACKINCRESIZE 10
#define Elemtype char
typedef struct SqStack{
Elemtype *top;
Elemtype *base;
int stacksize;
};
int Compare(SqStack &S) //判断括号是否合法 合法则返回1 否则返回0
{
char c1,c2;
if(S.top-S.base<2) printf("ERROR");
c1=*(S.top-1);
c2=*(S.top-2);
if(c1==')'&&c2=='('||c1==']'&&c2=='[')
return 1;
else
return 0;
}
void InitStack(SqStack &S) //初始化栈
{
S.base=(Elemtype*)malloc(STACK_INIT_SIZE*sizeof(Elemtype));
if(S.base==0) printf("内存分配错误");
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
}
void pop(SqStack &S)
{
S.top--;
}
void push(SqStack &S,Elemtype e) //入栈
{
if((S.top-S.base)>=S.stacksize)
{
S.base=(Elemtype*)realloc(S.base,(STACKINCRESIZE+S.stacksize)*sizeof(Elemtype));
if(S.base==0)
printf("内存分配错误");
S.stacksize+=STACKINCRESIZE;
S.top=S.base+S.stacksize;
}
*(S.top++)=e;
}
int Stackemtpy(SqStack &S) // 判断是否空栈
{
if(S.top==S.base) return 1;
else return 0;
}
void main()
{
int i=0;
int t;
char c[7];
SqStack S;
InitStack(S);
while(i<8) //输入符号 并且入栈
{
printf("\n please input:");
scanf("%c",&c[i]);
push(S,c[i]);
if(Compare(S)==1) //判断括号是否成对 如果成对就一起出栈
{
pop(S);
pop(S);
}
i++;
}
if(Stackemtpy(S)==0) printf("括号不合法");
else printf("括号合法");
}
没有错误 能运行 但是就是输入符号的方面出现了问题 求各位大神指教指教!!
[解决办法]
每次scanf之前把缓冲区清空一下
fflush(stdin);
scanf("%c",&c[i]);
对于你代码的功能上的问题,自己再分析分析吧。