文档章节

c语言删除注释

好铁
 好铁
发布于 2014/09/07 16:19
字数 1046
阅读 434
收藏 6
c
搬运自k&r习题解答:
/*
 * delete comment in C
 */
#include<stdio.h>

#define normal 0

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());
    }
    putchar(d);
}


书中答案rcomment函数中的

else if (d == '/') {
			putchar(c);
			rcomment(d);
		}
这个语句看了好久没没明白什么意思,测试程序的话,不处理'//'注释,只删除/*  */之间的,不敢确定是不是答案有问题。 

估计这是原本应该删除//到换行之间的注释的,若是这样,这个语句应改为:

else if (d == '/') {
			while(getchar()!='\n');
		}


不知道机械工业的那本中文答案是否可靠,在网上搜到一个英文版本答案,皮皮书屋可以下到chm版的,大概500多页,感觉这个答案比较好,有的题目有好几个解决办法,应对的情况也更详细。

再贴几个:

From Rick Dearman

Now handles "/* comment in string */" correctly, but does not remove the comment from

  return /* comment inside return statement */ 0;



/******************************************************
"Write a program to remove all comments from a C program. 
Don't forget to handle quoted strings and character 
constants properly. C comments do not nest."

Author: Rick Dearman (rick@ricken.demon.co.uk) 
******************************************************/

#include <stdio.h>

#define MAXLINE 1000 /* max input line size */
char line[MAXLINE]; /*current input line*/

int getline(void);  /* taken from the KnR book. */


int
main()
{
  int in_comment,len;
  int in_quote;
  int t;
  
  in_comment = in_quote = t = 0;
  while ((len = getline()) > 0 )
    {
      t=0;
      while(t < len)
        {
	  if( line[t] == '"')
		in_quote = 1;

	  if( ! in_quote )
	  {
          	if( line[t] == '/' && line[t+1] == '*')
            	{
              		t=t+2;
              		in_comment = 1;
            	}
          	if( line[t] == '*' && line[t+1] == '/')
            	{
              		t=t+2;
              		in_comment = 0;
            	}
          	if(in_comment == 1)
           	 {
              		t++;
            	}
          	else
            	{
              		printf ("%c", line[t]);
              		t++;
            	}
	  } 
	  else
	  {
              printf ("%c", line[t]);
              t++;
	  }
        }
    }
  return 0;
}


/* getline: specialized version */
int getline(void)
{
  int c, i;
  extern char line[];
  
  for ( i=0;i<MAXLINE-1 && ( c=getchar()) != EOF && c != '\n'; ++i)
    line[i] = c;
  if(c == '\n') 
    {
      line[i] = c;
      ++i;
    }
  line[i] = '\0';
  return i;

}




From Ben Pfaff

This version is a bugfix for the code var/'\2'

/* K&R2 1-23: Write a program to remove all comments from a C program.
   Don't forget to handle quoted strings and character constants
   properly.  C comments do not nest.

   This solution does not deal with other special cases, such as
   trigraphs, line continuation with \, or <> quoting on #include,
   since these aren't mentioned up 'til then in K&R2.  Perhaps this is
   cheating.

   Note that this program contains both comments and quoted strings of
   text that looks like comments, so running it on itself is a
   reasonable test.  It also contains examples of a comment that ends
   in a star and a comment preceded by a slash.  Note that the latter
   will break C99 compilers and C89 compilers with // comment
   extensions.

   Interface: The C source file is read from stdin and the
   comment-less output is written to stdout. **/

#include <stdio.h>

int
main(void)
{
#define PROGRAM 0
#define SLASH 1
#define COMMENT 2
#define STAR 3
#define QUOTE 4
#define LITERAL 5

    /* State machine's current state, one of the above values. */
    int state;

    /* If state == QUOTE, then ' or ".  Otherwise, undefined. */
    int quote;

    /* Input character. */
    int c;

    state = PROGRAM;
    while ((c = getchar()) != EOF) {
        /* The following cases are in guesstimated order from most common
           to least common. */
        if (state == PROGRAM || state == SLASH) {
            if (state == SLASH) {
                /* Program text following a slash. */
                if (c == '*')
                    state = COMMENT;
                else {
                    putchar('/');
                    state = PROGRAM;
                }
            }

            if (state == PROGRAM) {
                /* Program text. */
                if (c == '\'' || c == '"') {
                    quote = c;
                    state = QUOTE;
                    putchar(c);
                }
                else if (c == "/*"[0])
                    state = SLASH;
                else
                    putchar(c);
            }
        }
        else if (state == COMMENT) {
            /* Comment. */
            if (c == "/*"[1])
                state = STAR;
        }
        else if (state == QUOTE) {
            /* Within quoted string or character constant. */
            putchar(c);
            if (c == '\\')
                state = LITERAL;
            else if (c == quote)
                state = PROGRAM;
        }
        else if (state == SLASH) {
        }
        else if (state == STAR) {
            /* Comment following a star. */
            if (c == '/')
                state = PROGRAM;
            else if (c != '*')
                state = COMMENT;
        }
        else /* state == LITERAL */ {
            /* Within quoted string or character constant, following \. */
            putchar(c);
            state = QUOTE;
        }
    }

    if (state == SLASH)
        putchar('/' //**/
                1);

    return 0;
}

/* 
   Local variables:
   compile-command: "checkergcc -W -Wall -ansi -pedantic knr123-0.c -o knr123-0"
   End: 
*/






From Lew Pitcher

/* Lew Pitcher <lpitcher@yesic.com> */

/*/
** derem - remove C comments
**
** (attempt to solve K&R Exercise 1-22)
**
** As I only have v1 copy of K&R, I cannot
** be sure what is covered in K&R ANSI chapter 1.
** So, I restrict myself to the components covered
** in K&R v1 chapter 1, but modified for requisite ANSI
** features (int main() and return value).
**
** Components covered in v1 K&R chapter 1 include:
**  while (), for (), if () else
**  getchar(), putchar(), EOF
**  character constants, character escapes
**  strings
**  array subscripting
**
** Not directly covered are
**  string subscripting ( "/*"[0] )
**  initializers ( int state = PROGRAM; )
**/

/*/*/

#include <stdio.h>

#define	PROGRAM		0
#define	BEGIN_COMMENT	1
#define	COMMENT		2
#define	END_COMMENT	3
#define	QUOTE		4

int main(void)
{
	int this_char, quote_char;
	int state;

	state = PROGRAM;

	while ((this_char = getchar()) != EOF)
	{
		if (state == PROGRAM)
		{
			if (this_char == '/')
				state = BEGIN_COMMENT;
			else if ((this_char == '"') || (this_char == '\''))
			{
				state = QUOTE;
				putchar(quote_char = this_char);
			}
			else	putchar(this_char);
		}
		else if (state == BEGIN_COMMENT)
		{
			if (this_char == '*')
				state = COMMENT;
			else
			{
				putchar('/'); /* for the '/' of the comment */
				if (this_char != '/')
				{
					state = PROGRAM;
					putchar(this_char);
				}
				else	state = COMMENT;	/* stuttered */
			}
		}
		else if (state == QUOTE)
		{
			putchar(this_char);
			if (this_char == '\\')
				putchar(getchar());	/* escaped character */
			else if (this_char == quote_char)
				state = PROGRAM;
		}
		else if (state == COMMENT)
		{
			if (this_char == '*')
				state = END_COMMENT;
		}
		else if (state == END_COMMENT)
		{
			if (this_char == '/')
				state = PROGRAM;
			else if (this_char != '*')	/* stuttered */
				state = COMMENT;
		}
	}

	return 0;
}



© 著作权归作者所有

好铁
粉丝 40
博文 266
码字总数 78926
作品 0
朝阳
程序员
私信 提问
加载中

评论(3)

Tonlin
Tonlin

引用来自“William_Sim”的评论

引用来自“William_Sim”的评论

测试博客评论

看了么

面膜
Tonlin
Tonlin

引用来自“William_Sim”的评论

测试博客评论

看了么
Tonlin
Tonlin
测试博客评论
一道有意思的C语言编程题

最近在看经典的C语言入门书籍K&R,虽然是一本入门书籍,可是其中的精妙之处却需要慢慢体会。其中的经典题很多,仔细琢磨一定会收获良多。 今天看到这样一道题:编写一个删除C语言程序中所有的...

砍柴1990
2014/07/28
0
0
Linux Shell脚本去掉几类常见文件中的注释

Linux操作系统中去掉各类文件中的注释这个功能比较常用,通常用在查看一个较长的文件,又不想看注释的情况。通常这些文件包括C语言编写的.c、.h文件、cpp文件、.xml文件、.sh shell脚本文件、...

urey_pp
2016/12/27
0
0
纯C语言学生管理系统(学生期末作业)

** 纯C语言学生管理系统(学生期末作业) ** 分为7大功能:增、删、查、改、预览、存储、导出 代码都加有注释,利于不懂的,理解 添加功能 删除功能如下: 查找功能 修改功能 浏览功能 导入本...

wumingxiaozuzha
01/06
0
0
数据结构之红黑树C源码实现与剖析

前言 红黑树作为一种经典而高级的数据结构,相信已经被不少人实现过,但是因为程序不够完善而无法运行,就是因为程序完全没有注释,初学者根本就看不懂。——这句话相对赞 此份红黑树的C源码...

SibylY
2013/07/31
259
1
Python处理文本在Linux和windows下有什么异同?

之前写过一段Perl脚本,可以一下子删除代码中的所有C语言注释。我大致浏览了一下Python的re模块,感觉差不多。依然是把一个C文件读成一个字符串然后使用sub()进行匹配删除。发现“/× ×/”注...

小灰笔记
2015/04/12
885
6

没有更多内容

加载失败,请刷新页面

加载更多

PostgreSQL 11.3 locking

rudi
今天
5
0
Mybatis Plus sql注入器

一、继承AbstractMethod /** * @author beth * @data 2019-10-23 20:39 */public class DeleteAllMethod extends AbstractMethod { @Override public MappedStatement injectMap......

一个yuanbeth
今天
10
1
一次写shell脚本的经历记录——特殊字符惹的祸

本文首发于微信公众号“我的小碗汤”,扫码文末二维码即可关注,欢迎一起交流! redis在容器化的过程中,涉及到纵向扩pod实例cpu、内存以及redis实例的maxmemory值,statefulset管理的pod需要...

码农实战
今天
4
0
为什么阿里巴巴Java开发手册中不建议在循环体中使用+进行字符串拼接?

之前在阅读《阿里巴巴Java开发手册》时,发现有一条是关于循环体中字符串拼接的建议,具体内容如下: 那么我们首先来用例子来看看在循环体中用 + 或者用 StringBuilder 进行字符串拼接的效率...

武培轩
今天
8
0
队列-链式(c/c++实现)

队列是在线性表功能稍作修改形成的,在生活中排队是不能插队的吧,先排队先得到对待,慢来得排在最后面,这样来就形成了”先进先出“的队列。作用就是通过伟大的程序员来实现算法解决现实生活...

白客C
今天
81
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部