/* 查找c语言程序中的基本语法错误,如圆括号、方括号、花括号不配对等.要正确处理
引号(包括单引号和双引号)、转义字符序列与注释 */
#include<stdio.h>
#define MAXSIZE 10000 //允许存储的程序最大长度
static int seek_error(char str[]);
int practice1_24(void)
{
char str[MAXSIZE] = { 0 };
int c, i = 0;
freopen("C:\\\\Users\\wwwzh\\Desktop\\data.in", "r", stdin);
freopen("C:\\\\Users\\wwwzh\\Desktop\\data.out", "w", stdout);
while ((c = getchar()) != EOF && i < MAXSIZE)
{
str[i] = c;
i++;
}
if (i == MAXSIZE)
{
printf("error\n");
return 0;
}
seek_error(str);
return 0;
}
extern int remove_comments(char str[]);
/* 检查圆括号、方括号、花括号不匹配 */
static int seek_error(char str[])
{
//1.复制一份
char s[MAXSIZE];
int i = 0;
while (str[i] != '\0')
{
s[i] = str[i];
i++;
}
s[i] = '\0';
//2.删除注释
remove_comments(s);
//3.把字符,字符串里的全部替换为空格
i = 0;
while (s[i] != '\0')
{
int j = i + 1;
//处理字符串
if (s[i] == '\"')
{
while (s[j] != '\"')
{
int count = 1;
if (s[j] == '\\' && s[j + 1] == '\"')
{
while (s[j - count] == '\\')
count++;
if (count % 2 == 1)
j++;
}
if (s[j] == '\0')
{
printf("缺少右双引号");
return -1;
}
j++;
}
while ((i + 1) <= (j - 1))
{
s[i + 1] = ' ';
i++;
}
i++;
}
//处理字符
else if (s[i] == '\'')
{
while (s[j] != '\'')
{
int count = 1;
if (s[j] == '\\' && s[j + 1] == '\'')
{
while (s[j - count] == '\\')
count++;
if (count % 2 == 1)
j++;
}
if (s[j] == '\0')
{
printf("缺少右单引号");
return -1;
}
j++;
}
while ((i + 1) <= (j - 1))
{
s[i + 1] = ' ';
i++;
}
i++;
}
i++;
}
//4.括号匹配,匹配成功全部替换
i = 0;
while (s[i]!='\0')
{
int j = i - 1;
//小括号匹配
if (s[i] == ')')
{
while (s[j] != '(')
{
j--;
if (j == -1)
{
break;
}
}
if(s[j]=='(')
s[i] = s[j] = ' ';
}
//中括号匹配
else if (s[i] == ']')
{
while (s[j] != '[')
{
j--;
if (j == -1)
{
break;
}
}
if (s[j] == '[')
s[i] = s[j] = ' ';
}
//大括号匹配
else if (s[i] == '}')
{
while (s[j] != '{')
{
j--;
if (j == -1)
{
break;
}
}
if (s[j] == '{')
s[i] = s[j] = ' ';
}
i++;
}
//5扫描,发现括号报错
i = 0;
while (s[i]!='\0')
{
if (s[i] == '(' || s[i] == ')')
{
printf("小括号未闭合\n");
}
else if (s[i] == '[' || s[i] == ']')
{
printf("中括号未闭合\n");
}
else if (s[i] == '{' || s[i] == '}')
{
printf("大括号未闭合\n");
}
i++;
}
printf("%s", s);
return 0;
}