0917 实验一 词法分析程序
1 #include <stdio.h>
2 #include <string.h>
3
4 char prog[80],token[8],ch;
5 int syn,p,m,n,sum;
6 char *rwtab[6]={"begin","if","then","while","do","end"};
7
8 void scaner(void);
9
10 main()
11 {
12 p=0;
13 printf("\n Please input the source code:\n");
14
15 do{
16 scanf("%c",&ch);
17 prog[p++]=ch;
18 }while(ch!='#');
19
20 p=0;
21 do{
22 scaner();
23 switch(syn)
24 {
25 case 11:
26 printf("( %d,%d )\n",syn,sum);
27 break;
28
29 case -1:
30 printf("you have input a wrong string\n");
31 //getch();
32 return 0;
33 break;
34
35 default:
36 printf("( %d,%s )\n",syn,token);
37 break;
38 }
39 }while(syn!=0);
40 //getch();
41 printf(" Over.\n");
42 }
43
44 void scaner(void)
45 {
46 sum=0;
47
48 for(m=0;m<8;m++)
49 token[m++]= NULL;
50
51 ch=prog[p++];
52 m=0;
53
54 while((ch==' ')||(ch=='\n'))
55 ch=prog[p++];
56
57 if(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A')))
58 {
59 while(((ch<='z')&&(ch>='a'))||((ch<='Z')&&(ch>='A'))||((ch>='0')&&(ch<='9')))
60 {
61 token[m++]=ch;
62 ch=prog[p++];
63 }
64
65 p--;
66 syn=10;
67
68 for(n=0;n<6;n++)
69 if(strcmp(token,rwtab[n])==0)
70 {
71 syn=n+1;
72 break;
73 }
74 }
75 else if((ch>='0')&&(ch<='9'))
76 {
77 while((ch>='0')&&(ch<='9'))
78 {
79 sum=sum*10+ch-'0';
80 ch=prog[p++];
81 }
82 p--;
83 syn=11;
84 }
85 else
86 {
87 switch(ch)
88 {
89 case '<':
90 token[m++]=ch;
91 ch=prog[p++];
92 if(ch=='=')
93 {
94 syn=22;
95 token[m++]=ch;
96 }
97 else
98 {
99 syn=20;
100 p--;
101 }
102 break;
103
104 case '>':
105 token[m++]=ch;
106 ch=prog[p++];
107 if(ch=='=')
108 {
109 syn=24;
110 token[m++]=ch;
111 }
112 else
113 {
114 syn=23;
115 p--;
116 }
117 break;
118
119 case '+':
120 token[m++]=ch;
121 ch=prog[p++];
122 if(ch=='+')
123 {
124 syn=17;
125 token[m++]=ch;
126 }
127 else
128 {
129 syn=13;
130 p--;
131 }
132 break;
133
134 case '-':
135 token[m++]=ch;
136 ch=prog[p++];
137 if(ch=='-')
138 {
139 syn=29;
140 token[m++]=ch;
141 }
142 else
143 {
144 syn=14;
145 p--;
146 }
147 break;
148
149 case '=':
150 token[m++]=ch;
151 ch=prog[p++];
152 if(ch=='=')
153 {
154 syn=25;
155 token[m++]=ch;
156 }
157 else
158 {
159 syn=18;
160 p--;
161 }
162 break;
163
164 case '*': syn=15;token[m++]=ch; break;
165 case '/': syn=16;token[m++]=ch; break;
166 case '(': syn=27;token[m++]=ch; break;
167 case ')': syn=28;token[m++]=ch; break;
168 case ';': syn=26;token[m++]=ch; break;
169 case '#': syn=0;token[m++]=ch; break;
170 case ':': syn=17;token[m++]=ch; break;
171 default: syn=-1; break;
172 }
173 }
174 token[m++]='\0';
175 }