读《C程序设计语言》笔记3

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

ps:未考虑去除C/C++中的单行注释符'//'后面的注释内容

1 /********
2 Description:
3 删除C语言中所有的注释语句
4 ******/
5 #include <stdio.h>
6 void rcomment(int c);
7 void in_comment(void);
8 void echo_quote(int c);
9
10 //remove all comments from a valid C program
11 int main()
12 {
13 int c;
14 while((c=getchar())!=100)
15 rcomment(c);
16 return 0;
17 }
18 //recomment:read each character,remove the comments
19 void rcomment(int c)
20 {
21 int d;
22 if(c=='/')
23 if((d=getchar())=='*')
24 in_comment(); //beginning comment
25 else if(d=='/')
26 {
27 putchar(c);
28 rcomment(d);
29 }
30 else
31 {
32 putchar(c);
33 putchar(d);
34 }
35 else if(c=='\'' || c=='"')
36 echo_quote(c);
37 else
38 putchar(c);
39 }
40 //in_comment:inside of a valid comment
41 void in_comment(void)
42 {
43 int c,d;
44 c=getchar(); //prev character
45 d=getchar(); //curr character
46 while(c!='*' || d!='/') //search for end
47 {
48 c=d;
49 d=getchar();
50 }
51 }
52 //echo_quote:echo characters within quotes
53 void echo_quote(int c)
54 {
55 int d;
56 putchar(c);
57 while((d=getchar())!=c)
58 {
59 putchar(d);
60 if(d=='\\')
61 putchar(getchar());
62 }
63 putchar(d);
64 }

程序执行如下:(显示效果不够人性化,没有相关输入输出提示信息)

小结:期间犯了一个错误:

1 void echo_quote(int c)
2 {
3 int d;
4 putchar(c);
5 while((d=getchar()!=c))
6 {
7 putchar(d);
8 if(d=='\\')
9 putchar(getchar());
10 }
11 putchar(d);
12 }

上面第5行代码中本来应该是while((d=getchar())!=c),写成上面的情况后while((d=getchar()!=c)),后果很严重

究其原因:逻辑运算法的优先级比赋值运算符的优先级要高,所以getchar()!=c为真的话,d=1,于是输出ASCII码为1的字符,也就是上面的笑脸。

接下来还需要后续改进程序,使其可以处理//这样的注释。

posted on 2011-07-12 12:46  Tony.Works  阅读(386)  评论(0编辑  收藏  举报