《C程序設計語言》 練習1-23

問題描述

  編寫一個刪除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 }

 

 

運行結果