c程序设计语言(第二版.新版)习题1_24

/* 查找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;
}

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值