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

由于没能理解题目意思 ,直接看看答案。

 1 #include <stdio.h>
 2 
 3 
 4 void rcomment(int c);
 5 void in_comment(void);
 6 void echo_quote(int c);
 7 
 8 /* remove all comment form a valid C program*/
 9 
10 
11 main()
12 {
13     int c, d;
14 while ((c = getchar()) != EOF)
15 
16     rcomment(c);
17     return 0;
18 }
19 
20 
21 /* rcomment : read each character, remove the comments*/
22 
23 void rcomment(int c)
24 {
25     int d;
26     if(c == '/')
27         if((d = getchar()) == '*')
28         in_comment();       /*beginning comment*/
29     else if (d == '/')
30     {
31         putchar(c);     /*another slash*/
32         rcomment(d);
33     }else
34     {
35         putchar(c);         /* not a  comment*/
36         putchar(d);
37     }
38     else if(c == '\'' || c == '""')
39         echo_quote(c);          /*quote begins */
40         else
41             putchar(c);         /*not a comment*/
42 }
43 
44 
45 
46 /*in_comment: inside of a valid comment*/
47 
48 void in_comment(void)
49 
50 {
51     int c, d;
52     c = getchar();      /*prev character*/
53     d = getchar();      /*curr character*/
54 while (c != '*' || d != '/')    /*search for end*/
55     {c = d;
56 d = getchar();
57 }
58 }
59 
60 
61 /*echo_quote : echo characters within quotes*/
62 
63 void echo_quote(int c)
64 {
65     int d;
66     putchar(c);
67 
68     while((d = getchar()) != c)    /*search for end*/
69     {
70         putchar(d);
71         if (d == '\\')
72             putchar(getchar());         /*ignore escape seq*/
73     }
74     putchar(d);
75 }

看完答案..对题目的要求清除..其实就是去掉注释形态的文字...起初我理解到了 从代码中进行处理..原来只是从程序运行中输入的内容进行处理。想多了。

posted @ 2013-10-27 15:14  _Jango  阅读(1170)  评论(0编辑  收藏  举报