int brace, brack, paren;
void in_mutli_comment()
{
int c = getchar();
int d = getchar();
// *a
while (!(c == '*' && d == '/')) {
c = d;
d = getchar();
}
}
void in_line_comment()
{
int c;
while ((c = getchar()) != '\n')
;
}
int in_quote(char c)
{
char d;
while (1) {
d = getchar();
if (d == '\\')
getchar();
if (d == c)
break;
}
}
void find(char c)
{
if (c == '{')
brace++;
else if (c == '[')
brack++;
else if (c == '(')
paren++;
else if (c == '}')
brace--;
else if (c == ']')
brack--;
else if (c == ')')
paren--;
}
int main(void)
{
int c;
while ((c = getchar()) != EOF) {
if (c == '/') {// 有可能进入注释
int d = getchar();
if (d == EOF) break;
if (d == '*') // 多行注释
in_mutli_comment();
else if (d == '/') // 单行注释
in_line_comment();
else
find(d);
}else if (c == '\'' || c == '"') { // 进入字符或字符串
in_quote(c);
} else {
find(c);
}
if (brace < 0) {
printf("大括号有问题\n");
brace = 0;
}
if (brack < 0) {
printf("中括号有问题\n");
brack = 0;
}
if (paren < 0) {
printf("中括号有问题\n");
paren = 0;
}
} // end while
if (brace > 0) {
printf("大括号有问题\n");
}
if (brack > 0) {
printf("中括号有问题\n");
}
if (paren > 0) {
printf("小括号有问题\n");
}
system("pause");
}
C语言|构造一个简易编译器检测括号是否正确
最新推荐文章于 2021-05-21 04:08:49 发布