代码改变世界

Getting started with the basics of programming exercises_4

2015-05-05 19:09  星星之火✨🔥  阅读(180)  评论(0)    收藏  举报

1、编写一个删除C语言程序中所有的注释语句的程序。要正确处理带引号的字符串与字符串常量,C语言中程序注释不允许嵌套。

#include<stdio.h>
void rcomment(int c);
void in_comment(void);
void echo_quote(int c);
// remove all comments from a valic C program
int main(void)
{
	int c;
	while((c = getchar()) != EOF)
		rcomment(c);
	
    return 0;
}
// rcomment: read each character,remove the comments
void rcomment(int c)
{
	int d;
	
	if(c == '/')
		if((d = getchar()) == '*')
			in_comment(); // beginning comment
		else if(d == '/')
		{
			putchar(c); // another slash
			rcomment(d);
		}
		else
		{
			putchar(c); // not a comment
			putchar(d);
		}
	else if(c == '\'' || c == '"')
		echo_quote(c); // quote begins
	else
		putchar(c); // not a comment
}
// in_comment: inside of a valid comment
void in_comment(void)
{
	int c, d;
	
	c = getchar(); // prev character
	d = getchar(); // curr character
	while(c != '*' || d != '/') // here can be more readable
	{
		c = d;
		d = getchar();
	}
}
// echo_quote: echo characters within quotes
void echo_quote(int c)
{
	int d;
	
	putchar(c);
	while((d = getchar()) != c) // search for end
	{
		putchar(d);
		if(d == '\\')
			putchar(getchar()); // ignore escape seq
	}
}

2、小型词法分析器

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

#include<stdio.h>
int brace, brack, paren;
void in_quote(int c);
void in_comment(void);
void search(int c);
// rudimentary syntax checker for C programs
int main(void)
{
	int c;
	extern int brace, brack, paren;
	while((c = getchar()) != EOF)
	{
		if(c == '/')
		{
			if((c = getchar()) == '*')
				in_comment(); // inside comment
			else
				search(c);
		}
		else if(c == '\'' || c == '"')
			in_quote(c); // inside quote
		else
			search(c);
		
		if(brace < 0) // output errors
		{
			printf("Unbalanced braces\n");
			brace = 0;
		}
		else if(brack < 0)
		{
			printf("Unbalanced brackets\n");
			brack = 0;
		}
		else if (paren < 0)
		{
			printf("Unbalanced parentheses\n");
		}
	}
	
	if(brace > 0) // output errors
		printf("Unbalanced braces\n");
	if(brack > 0)
		printf("Unbalanced brackets\n");
	if(paren > 0)
		printf("Unbalanced parentheses\n");
	
	return 0;
}

// search: search for rudimentary syntax errors
void search(int c)
{
	extern int brace, brack, paren;
	
	if(c == '{')
		++brace;
	else if(c == '}')
		--brace;
	else if(c == '[')
		++brack;
	else if(c == ']')
		--brack;
	else if(c == '(')
		++paren;
	else if(c == ')')
		--paren;	
}

// in_comment: inside of a valid comment
void in_comment(void)
{
	int c, d;
	
	c = getchar(); // pre character
	d = getchar(); // curr character
	while(c != '*' || d != '/')
	{
		c = d;
		d = getchar();
	}
}

// in_quote: inside quote
void in_quote(int c)
{
	int d;
	
	while((d = getchar()) != c) // search end quote
		if(d == '\\')
			getchar(); // ignore escape seq
}