标签:
词法分析程序的功能:
提示用户输入一段需分析的源程序,然后程序读入该源程序的字符串进行词法分析,最后输出词法分析的结果显示在屏幕上。
符号与种别码对照表:
单词符号 种别码 单词符号 种别码
begin 1 : 17
if 2 := 18
then 3 < 20
while 4 <= 22
do 5
end 6 > 23
l(l|d)* 10 >= 24
dd* 11 = 25
+ 13 ; 26
- 14 ( 27
* 15 ) 28
/ 16 # 0
<字母>
S->a|b|c||d|.....y|z|
<数字>
D->1|2|3|...|8|9|
S->D|SD|S0|
<标识符>
A->1|2|3|...|8|9|
B->a|b|c|...|y|z|
S->AB
<关键字>
B->a|b|c|...|y|z|
S->B|AB|
<运算符>s
A->+|-|*|/|
<界符>
D->:|;|...|<|=|
S->D|SD|
1 #include<stdio.h> 2 #define MAX 100 3 char ch,zifu[MAX],linshi[15]; 4 int zhongbie,p;/*zhongbie代表字符种别,p代表数组zifi的下标位置*/ 5 void cwh(); 6 main() 7 { 8 p=0; 9 gets(zifu); 10 do{ 11 cwh(); 12 if(zhongbie==-1) 13 continue; 14 printf("<%d,",zhongbie); 15 printf("%s>\n",linshi); 16 }while(zhongbie!=-1); 17 } 18 void cwh() 19 { 20 int i,m;/*m用于记录linshi的下标*/ 21 char *guanjianzi[6]={"begin","if","then","while","do","end"};/*char*[]数组每个元素指向一个char型的变量,关键字数组记得zhongbie+1*/ 22 char shuangfuhao[2]={‘1‘,‘1‘};/*字符=1*/ 23 zhongbie=-1; 24 for(i=0;i<15;i++) 25 { linshi[i]=NULL;}/*定义一个临时存放字符串的数组用作比较*/ 26 do 27 { 28 m=0;/*初始化下标*/ 29 ch=zifu[p++]; 30 /*开始识别字符种别*/ 31 while(ch==‘ ‘) 32 { 33 ch=zifu[p++]; 34 } 35 /*识别关键字或者标识符*/ 36 if((ch>=‘a‘&&ch<=‘z‘)||(ch>=‘A‘&&ch<=‘Z‘)) 37 { 38 while((ch>=‘0‘&&ch<=‘9‘)||(ch>=‘a‘&&ch<=‘z‘)||(ch>=‘A‘&&ch<=‘Z‘))/*将标识符存入临时数组*/ 39 { 40 linshi[m++]=ch; 41 ch=zifu[p++]; 42 } 43 zhongbie=10;/*p=p+1下次识别就是p+1*/ 44 for(i=0;i<6;i++) /*将识别出来的字符和已定义的关键字作比较 */ 45 { 46 if(strcmp(linshi,guanjianzi[i])==0) 47 { 48 zhongbie=i+1; 49 break; 50 } 51 } 52 break; 53 } 54 /*识别数字*/ 55 else if((ch>=‘0‘&&ch<=‘9‘)) 56 { 57 while((ch>=‘0‘&&ch<=‘9‘)) 58 { 59 linshi[m++]=ch; 60 ch=zifu[p++]; 61 } 62 zhongbie=11; 63 break; 64 } 65 else 66 { 67 switch(ch) 68 { 69 case ‘:‘: 70 linshi[m++]=ch; 71 ch=zifu[p++]; 72 if(ch==‘=‘) 73 { 74 zhongbie=18; 75 linshi[m++]=ch; 76 } 77 else 78 { zhongbie=17;} 79 break; 80 case ‘<‘: 81 linshi[m++]=ch; 82 ch=zifu[p++]; 83 if(ch==‘=‘) 84 { 85 zhongbie=21; 86 linshi[m++]=ch; 87 } 88 else if(ch==‘>‘) 89 { 90 zhongbie=22; 91 linshi[m++]=ch; 92 } 93 else 94 { zhongbie=20;} 95 break; 96 case ‘>‘: 97 linshi[m++]=ch; 98 ch=zifu[p++]; 99 if(ch==‘=‘) 100 { 101 zhongbie=24; 102 linshi[m++]=ch; 103 } 104 else 105 { zhongbie=23;} 106 break; 107 case ‘+‘:zhongbie=13;linshi[0]=ch;break; 108 case ‘-‘:zhongbie=14;linshi[0]=ch;break; 109 case ‘*‘:zhongbie=15;linshi[0]=ch;break; 110 case ‘/‘:zhongbie=16;linshi[0]=ch;break; 111 case ‘=‘:zhongbie=25;linshi[0]=ch;break; 112 case ‘;‘:zhongbie=26;linshi[0]=ch;break; 113 case ‘(‘:zhongbie=27;linshi[0]=ch;break; 114 case ‘)‘:zhongbie=28;linshi[0]=ch;break; 115 case ‘#‘:zhongbie=0;linshi[0]=ch;break; 116 } 117 break; 118 } 119 }while(zhongbie!=-1); 120 }
标签:
原文地址:http://www.cnblogs.com/lsq141205/p/5937033.html