练习1-24: 编写一个程序,查找C语言程序中的基本语法错误,如圆括号,方括号以及花括号不配对等。要正确的处理引号(包括单引号,双引号)~转移字符序列与注释(如果读者想把该程序编写成完全通用的程序,难度会比较大。)

大概能理解题目意思,程序需要检测,输入的内容中,括号对等(检测到头括号,必须要检测到尾括号对应,否则报错),引号对称等处理内容。

 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         }else if(c == '\'' || c == '""')
25         in_quote(c);/*inside quote*/
26 else
27     search(c);
28 if(brace < 0)   /*output errors*/
29 {
30 printf("Unbalanced braces\n");
31 brace = 0;
32 }else if (brack < 0)
33 {
34 
35 printf("Unbalanced brackets\n");
36 brack = 0;
37 }else if (paren < 0)
38 {
39 printf("Unalanced parentheses\n");
40 paren = 0;
41     }
42     }       /*output errrors*/
43     if(brace > 0)
44         printf("Unbalanced braces\n");
45     if(brack >0)
46         printf("Unbalanced brackets\n");
47     if(paren > 0)
48         printf("Unbalanced parentheses\n");
49     return 0;
50 }
51 
52 /*search: search fo rudimentary syntax eorrors*/
53 void search(int c)
54 {
55 extern int brace, brack, paren;
56 if(c == '{')
57     ++brace;
58 else if(c == '}')
59     --brace;
60 else if(c == '[')
61     ++brack;
62 else if(c == ']')
63     --brack;
64 else if(c == '(')
65      ++paren;
66 else if(c == ')')
67     --paren;
68 }
69 /*in_comment : inside of a valid comment*/
70 void in_comment(void)
71 {
72 int c, d;
73 c = getchar();
74 d = getchar();
75 while(c != '*' || c != '/')
76 {
77     c = d;
78     d = getchar();
79 }
80 }
81 /*in_quote: inside quote*/
82 void in_quote(int c)
83 {
84     int d;
85     while((d = getchar()) != c)
86         if(d == '\\')
87         getchar();
88 }

 

posted @ 2013-10-27 16:41  _Jango  阅读(1091)  评论(0编辑  收藏  举报