练习1-24.编写一个程序来判断C程序的基本情况 语法错误,如不匹配的圆括号、方括号和大括号.别 忘记引号,包括单引号和双引号,转义序列 comments .(如果你完全泛泛地做这个程序,这个程序会很难.)
这是我为该程序编写的代码(它还没有完成,我稍后将对其进行更多的工作):
#include <stdio.h>
#define YES 1
#define NO 0
int a = 0;
void push(int stack[], int c);
void pull(int stack[]);
int check(int stack[], int c);
int main()
{
int stack[1000], c, keep = 1;
extern int a;
while ((c = getchar()) != EOF && keep == YES)
{
if (c == '[' || c == '(' || c == '{')
push(stack, c);
else if (c == ']' || c == ')' || c == '}')
keep = check(stack, c);
}
return 0;
}
void push(int stack[], int c)
{
int i;
for (i = a; i; --i)
stack[i+1] = stack[i];
++a;
stack[0] = c;
}
void pull(int stack[])
{
int i;
--a;
for (i = 0; i < a; ++i)
stack[i] = stack[i+1];
stack[a] = '\0';
}
int check(int stack[], int c)
{
if ((c == ']' && stack[0] == '[') || (c == ')' && stack[0] == '(') || (c == '}' && stack[0] == '{'))
{
pull(stack);
return YES;
}
else
{
printf("Mismatched character: '%c'\n", c);
return NO;
}
}
当我给它一个类似{}
或( ) () {} []
的输出时,它可以工作,但当我给它类似(())
的输出时,它会给我这个输出: