1 #include <stdio.h>
 2 
 3 int brace, brack, paren;
 4 
 5 void in_quote(int c);
 6 void in_comment(viod);
 7 void search(int c);
 8 
 9 /* rudimentary syntax checker for C programs*/
10 
11 main()
12 {
13     int c;
14     extern int brace, brack, paren;
15 
16     while ((c = getchar()) != EOF)
17     {
18         if(c == '/')
19         {
20             if((c = getchar()) == '*')
21                 in_comment();   /*inside comment*/////去掉注释
22             else
23                 search(c);
24         }
25         else if(c == '\'' || c == '""')
26             in_quote(c);/*inside quote*/
27         else
28             search(c);
29 
30         if(brace < 0)   /*output errors*/
31         {
32             printf("Unbalanced braces\n");
33             brace = 0;
34         }
35         else if (brack < 0)
36         {
37 
38             printf("Unbalanced brackets\n");
39             brack = 0;
40         }
41         else if (paren < 0)
42         {
43             printf("Unalanced parentheses\n");
44             paren = 0;
45         }
46     }       /*output errrors*/
47     if(brace > 0)
48         printf("Unbalanced braces\n");
49     if(brack >0)
50         printf("Unbalanced brackets\n");
51     if(paren > 0)
52         printf("Unbalanced parentheses\n");
53     return 0;
54 }
55 
56 /*search: search fo rudimentary syntax eorrors*/
57 void search(int c)
58 {
59     extern int brace, brack, paren;
60     if(c == '{')
61         ++brace;
62     else if(c == '}')
63         --brace;
64     else if(c == '[')
65         ++brack;
66     else if(c == ']')
67         --brack;
68     else if(c == '(')
69          ++paren;
70     else if(c == ')')
71         --paren;
72 }
73 /*in_comment : inside of a valid comment*/
74 void in_comment(void)
75 {
76     int c, d;
77     c = getchar();
78     d = getchar();
79     while(c != '*' || c != '/')
80     {
81         c = d;
82         d = getchar();
83     }
84 }
85 /*in_quote: inside quote*/
86 void in_quote(int c)
87 {
88     int d;
89     while((d = getchar()) != c)
90         if(d == '\\')
91         getchar(); //将\后的一个字符忽略掉  不进行上面的while里面的判断 防止是引号继而跳出这个while循环
92 }

 

posted on 2020-04-26 15:28  杪杪  阅读(456)  评论(0)    收藏  举报