首页 > 编程语言 > 详细

《C程序设计语言》 练习1-23

时间:2020-05-05 13:15:39      阅读:73      评论:0      收藏:0      [点我收藏+]

问题描述

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

  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.

 

解题思路

1.我们要知道注释有两种,一种是单行注释(//123456),另一种是多行注释(/*123456*/)

2.开始进入单行注释的标志是,遇到两个斜杠‘ // ’ , 结束标志是换行 ‘ \n ‘

3.开始进入多行注释的标志是,遇到 ‘ /* ‘ ,  结束标志是  ‘ */ ‘

4.所以我们设置一个变量来判断字符在注释内还是注释外,注释内不输出,注释外输出

5.如果出现这种语句:

 

printf("注释语句为/*123456*/");

 

  双引号内的内容是要打印的,要输出

6.所以我们要保证,在判断注释语句的标志时,字符不在双引号内

 

 

代码实现

 

 1 #include<stdio.h>
 2 #define MAXLEN 1024
 3 
 4 int getlines(int array[] , int maxlen);//将输入读入数组
 5 
 6 int main()
 7 {
 8     int array[MAXLEN];
 9     int len;
10     int i=0;
11     int in_quote=0;//判断是否在引用内
12     int in_commentm=0;//判断是否在多行注释内
13     int in_comment;//判断是否在单行注释内
14     while ((len = getlines(array , MAXLEN)) > 0)
15     {
16         while(i < len)
17         {
18             if (array[i]==")
19             {
20                 in_quote = 1;
21             }
22             if (in_quote==1 && array[i]==")
23             {
24                 in_quote = 0;
25             }
26             
27             if (in_quote==0)
28             {
29                 if (array[i] == / && array[i+1] == *)
30                 {
31                     i = i+2;
32                     in_commentm = 1;
33                 }
34                 if (array[i] == / && array[i+1] == /)
35                 {
36                     i = i+2;
37                     in_comment = 1;
38                 }
39                 if (array[i]==\n)
40                 {
41                     in_comment = 0;
42                 }
43                 
44                 
45                 if (array[i] == * && array[i+1] == /)
46                 {
47                     i = i+2;
48                     in_commentm = 0;
49                 }
50                 if (in_commentm==1 || in_comment==1)//注释内的字符全部略过,不输出
51                 {
52                     i++;
53                 }else
54                 {
55                     printf("%c",array[i]);
56                     i++;
57                 }
58             }else
59             {
60                 printf("%c",array[i]);
61                 i++;
62             }
63         }
64         i = 0;
65     }
66     return 0;
67 }
68 
69 
70 int getlines(int array[] , int maxlen)
71 {
72     int c,i;
73     for ( i = 0; i < maxlen-1 && (c=getchar())!=EOF; i++)
74     {
75         array[i] = c;
76     }
77     array[i] = \0;
78     return i;
79 }

 

 

运行结果

技术分享图片

 

《C程序设计语言》 练习1-23

原文:https://www.cnblogs.com/jerryleesir/p/12830281.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!