C语言-删除注释

C语言中的注释,不嵌套,一律使用/*   */的形式。不过双引号中的/*  */则不能算是注释。

以下是正确的代码

/*
 * ==================================================
 *
 *       Filename:  1-23.c
 *
 *    Description:  删除c风格的注释,读入的数据为.c程序源代码
 *					copy自The C Answer Book
 *
 *        Version:  0.01
 *        Created:  2013年09月07日 星期六 10时34分45秒
 *         Author:  HaxtraZ, zchrissirhcz@163.com
 *        Company:  ZJUT
 *
 * ==================================================
 */
#include

void rcomment(int c);
void in_comment(void);
void echo_quote(int c);

main() {
	int c;

	while ((c=getchar()) != EOF)
		rcomment(c);
	return 0;
}

void rcomment(int c) {
	int d;

	if (c=='/') {
		if ((d=getchar())=='*')
			in_comment();
		else if (d=='/')  {
			putchar(c);
			rcomment(d);
		} else {
			putchar(c);
			putchar(d);
		}
	} else if (c=='\'' || c=='"')
		echo_quote(c);
	else
		putchar(c);
}

void in_comment(void) {
	int c, d;

	c = getchar();
	d = getchar();
	while (c!='*' || d!='/') {
		c = d;
		d = getchar();
	}
}

void echo_quote(int c) {
	int d;

	putchar(c);
	while ((d=getchar())!=c) {
		putchar(d);
		if (d=='\\')
			putchar(getchar());
		/*这一句是处理转义的单引号或者双引号(由c决定)
		 * 例如,printf("Nice\"day!");一句,如果不处理,则会进死循环*/
	}
	putchar(d);
}

  

posted @ 2013-09-07 11:06  ChrisZZ  阅读(1972)  评论(0编辑  收藏  举报