练习 1-24 编写一个程序,查找C语言程序中的基本语法错误,如圆括号、方括号、花括号不配对等。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/navicheung/article/details/86098643

C语言程序设计(第二版) 练习1-24 个人设计

练习 1-24 编写一个程序,查找C语言程序中的基本语法错误,如圆括号、方括号、花括号不配对等。要正确处理引号(包括单引号和双引号)、转义字符序列与注释。

代码块:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void judge(char s[]);                               //定义判断函数
int main()
{
	char string[1000];                              //定义一个足够大的字符串数组
	int i;
	printf("Please enter code:\n");                 //输入程序代码
	for (i=0; (string[i]=getchar())!=EOF; i++);
	string[i]='\0';
	judge(string);                                  //调用判断函数
	system("pause");
	return 0;
}
/*判断函数*/
void judge(char s[])
{
	/*定义变量,j,k,m,n,x,y为三种括号的数组下标变量,
	len为程序字符串长度,str是判断是否在程序的字符串内,note是判断是否在注释内*/
	int i, j, k, m, n, x, y, len, str, note;
	/*下行是容纳三种括号判断标志的数组*/
	int a[100], b[100], c[100], d[100], e[100], f[100];
	int s1, s2, s3;
	len=strlen(s);
	for (i=0, j=0, m=0, x=0, str=0, note=0; i<=len; i++){
		if (s[i]=='"')                              //27-28行,用于后面判断是否在程序的字符串内
			str++;
		if (s[i]=='/'&&s[i+1]=='/'&&str%2==0)       //29-36行,用于后面判断是否在程序的注释内
			note=1;
		else if (s[i]=='\n')
			note=0;
		if (s[i]=='/'&&s[i+1]=='*'&&str%2==0)
			note=1;
		else if (s[i]=='/'&&s[i+1]=='\n')
			note=0;
		if (s[i]=='('&&str%2==0&&note==0){          //37-55行,判断圆括号
			a[j]=1, b[j]=0;
			j++;
		}
		if (s[i]==')'&&str%2==0&&note==0){
			if (j==0){
				a[j]=0, b[j]=1;
				j++;
			}
			else{
				for (k=j-1; b[k]==1; k--);
				if (k==-1){
					a[j]=0, b[j]=1;
					j++;
				}
				else
					b[k]=1;
			}
		}
		if (s[i]=='['&&str%2==0&&note==0){          //56-75行,判断方括号
			c[m]=1, d[m]=0;
			m++;
		}
		if (s[i]==']'&&str%2==0&&note==0){
			if (m==0){
				c[m]=0, d[m]=1;
				m++;
			}
			else{
				for (n=i-1; s[n]>='0'&&s[n]<='9'; n--);
				if (s[n]=='['){
					d[m-1]=1;
				}
				else{
					c[m]=0, d[m]=1;
					m++;
				}
			}
		}
		if (s[i]=='{'&&str%2==0&&note==0){          //76-94行,判断花括号
			e[x]=1, f[x]=0;
			x++;
		}
		if (s[i]=='}'&&str%2==0&&note==0){
			if (x==0){
				e[x]=0, f[x]=1;
				x++;
			}
			else{
				for (y=x-1; f[y]==1; y--);
				if (y==-1){
					e[x]=0, f[x]=1;
					x++;
				}
				else
					f[y]=1;
			}
		}
	}
	/*97-113行,只要条件符合,输出错误,否则程序没有问题*/
	for (i=0, s1=0; i<j; i++)
		if (a[i]==0||b[i]==0){
			printf("The No.%d ykh is wrong!\n", i+1);
			s1=1;
		}
	for (i=0, s2=0; i<m; i++)
		if (c[i]==0||d[i]==0){
			printf("The No.%d fkh is wrong!\n", i+1);
			s2=1;
		}
	for (i=0, s3=0; i<x; i++)
		if (e[i]==0||f[i]==0){
			printf("The No.%d hkh is wrong!\n", i+1);
			s3=1;
		}
	if (s1==0&&s2==0&&s3==0)
		printf("No problem!\n");
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/86098643
今日推荐