删除C语言程序中所以的注释语句(有疑问)

     源自《The C Programming Language》P25 p1-23:

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

     参考代码:

     

main.c
1 /*
2 #include <stdio.h>
3
4 #define MAXLINE 1000
5
6 int getLine(char s[], int lim);
7 void copy(char to[], char from[]);
8 void delNotes(char **s, int row);
9
10 int main()
11 {
12
13 int c, len, row, index;
14 char line[MAXLINE];
15 char code[MAXLINE][MAXLINE];
16
17 row = 0;
18 while((len = getLine(line, MAXLINE)) >= 0)
19 copy(code[row++], line);
20 delNotes(code, --row);
21
22 return 0;
23 }
24
25 int getLine(char s[], int lim)
26 {
27 int c, i;
28
29 for(i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
30 s[i] = c;
31 if(c == '\n')
32 {
33 ++i
34 s[i] = c;
35 ++i;
36 }
37 s[i] = '\0';
38
39 return i;
40
41 }
42
43 void copy(char to[], char from[])
44 {
45 int i;
46
47 i = 0;
48 while((to[i] = from[i]) != '\0')
49 ++i;
50 }
51
52 void delNotes(char **s, int row)
53 {
54 int i;
55
56 i = 0;
57 while(i <= row)
58 {
59 int j;
60
61 for(j = 0; s[i][j] != '\0'; ++j)
62 if(s[i][j] == '/')
63 if(s[i][j+1] == '/')
64 {
65 s[i][j] == '\n';
66 s[i][j+1] == '\0';
67 }
68 else if(s[i][j+1] == '*')
69 {
70
71 }
72 }
73 }
74 */
75
76 #include <stdio.h>
77
78 void rcomment(int c);
79 void in_comment();
80 void echo_quote(int c);
81
82 int main()
83 {
84
85 int c, d;
86
87 while((c = getchar()) != EOF)
88 rcomment(c);
89
90 return 0;
91 }
92
93 void rcomment(int c)
94 {
95 int d;
96
97 if(c == '/')
98 if((d = getchar()) == '*')
99 in_comment();
100 else if(d == '/')
101 {
102 //putchar(c);
103 //rcomment(d);
104 fflush(stdin);
105 putchar('\n');
106 }
107 else
108 {
109 putchar(c);
110 putchar(d);
111 }
112 else if(c == '\'' || c == '\"')
113 echo_quote(c);
114 else
115 putchar(c);
116 }
117
118 void in_comment()
119 {
120 int c, d;
121
122 c = getchar();
123 d = getchar();
124 while(c != '*' || d != '/')
125 {
126 c = d;
127 d = getchar();
128 }
129 }
130
131 void echo_quote(int c)
132 {
133 int d;
134
135 putchar(c);
136 while((d = getchar()) != c)
137 {
138 putchar(d);
139 if(d == '\\') //这个判断条件不要,好像也没有影响?
140 putchar(getchar());
141 }
142 putchar(d);
143 }

     分析:

     1,  当输入:int a = 9;/*variant a equal 9时,调用main函数中的while循环中的rcomment函数,在终端的下一行

          输出:int a = 9;,当c == '/',d == '*'时,进入in_comment函数,则后面的"variant a equal 9"不输出在终端,

          最终光标停在int a = 9;中';'字符后面等待下一次输入(此时仍在执行in_comment函数,并未跳出)。

          当再次输入:comment*/end时,继续接着执行in_comment函数中的while循环(因为处理完上次输入后,

          并未跳出in_comment函数中的while循环),故不会输入"comment",当读入'*'和'/',in_comment函数

          中的while条件不满足了,跳出in_comment,跳回到rcomment中,接着跳回到main中的while循环中,从

          输入缓冲区中读入"end",输出到终端的下一行。

    疑问:

  1,  echo_quote函数:if(d == '//') putchar(getchar()); 的作用?

posted on 2011-04-27 01:21  将军之盾  阅读(836)  评论(0编辑  收藏  举报