实验:词法分析
一.实验目的:编写一个词法分析
实验要求:输入:源程序字符串
输出:二元组(种别,单词本身)
二.词法分析程序设计
词法规则:字母<a|b|c|...|z>
数字<0|1|2|...|9>
整数常数:<数字>
标识符:<变量〉
关键字:<main|scanf|printf|...|const>
运算符:<+|-|*|...|:=>
界符 :<(|)|,|;|.>
各单词对应的种别码
三:源代码展示
1 #include<stdio.h> 2 #include<malloc.h> 3 #include<stdlib.h> 4 #include<ctype.h> 5 typedef struct node 6 { 7 char ch; 8 struct node *next; 9 }QNode,*QueuePtr; 10 11 typedef struct 12 { 13 QueuePtr front; 14 QueuePtr rear; 15 }LinkQueue; 16 17 LinkQueue Q; 18 QueuePtr p; //定义一个指针变量 19 char *keyword[30]={"main","scanf","printf","void","int","float","double","char","long","short","signed", 20 "struct","do","while","for","switch","case","break","continue","if","define","typedef","union", 21 "static","sizeof","return","extern","goto","auto","const"}; 22 char *operatornum[6]={"+","-","*","/","++","--"}; 23 char *comparison[8]={"<","<=","=",">",">=","<>","==","!="}; 24 char *interpunction[8]={",",";",":=",".","(",")","{","}"}; 25 char *biaoshifu[6]={"%","$","^","&","_","#"}; //特殊标识符 26 char *zhushifu[3]={"//","/*","*/"}; //注释符 27 char *luoji[3]={"&&","||","!"}; //逻辑运算符 28 char *k=""; 29 30 void InitQueue() //初始化一个带节点的空队列 31 { 32 Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode)); 33 if(!Q.front) 34 exit(0); 35 Q.front->next=NULL; 36 } 37 void Printf() 38 { 39 QueuePtr p; //定义一个指针变量 40 p=Q.front; 41 while(!(p==Q.rear)) 42 { 43 p=p->next; 44 printf("%c",p->ch); 45 } 46 printf(" "); 47 } 48 void Creat() //创建队列 49 { 50 char ch; 51 QueuePtr p; 52 printf("请输入您要分析的字符串"); 53 ch=getchar(); 54 while(ch!='@') 55 { 56 p=(QueuePtr)malloc(sizeof(QNode)); 57 p->ch=ch; 58 p->next=NULL; 59 Q.rear->next=p; 60 Q.rear=p; 61 ch=getchar(); 62 } 63 } 64 65 66 int search(char searchstr[],int wordtype)//符号匹配 67 { 68 int i; 69 switch (wordtype) 70 { 71 case 1: 72 for(i=0;i<30;i++) 73 { 74 if(strcmp(keyword[i],searchstr)==0) 75 return i; 76 } 77 break; 78 case 2: 79 for(i=0;i<=5;i++) 80 { 81 if(strcmp(operatornum[i],searchstr)==0) 82 return 30+i; 83 } 84 break; 85 86 case 3: 87 for(i=0;i<=7;i++) 88 { 89 if(strcmp(comparison[i],searchstr)==0) 90 return 36+i; 91 } 92 break; 93 94 case 4: 95 for(i=0;i<=7;i++) 96 { 97 if(strcmp(interpunction[i],searchstr)==0) 98 return 44+i; 99 } 100 101 break; 102 case 5: 103 for(i=0;i<=5;i++) 104 { 105 if(strcmp(biaoshifu[i],searchstr)==0) 106 return 52+i; 107 } 108 break; 109 case 6: 110 for(i=0;i<=2;i++) 111 { 112 if(strcmp(zhushifu[i],searchstr)==0) 113 return 58+i; 114 } 115 break; 116 case 7: 117 for(i=0;i<=2;i++) 118 { 119 if(strcmp(luoji[i],searchstr)==0) 120 return 61+i; 121 } 122 break; 123 } 124 125 return -1; 126 } 127 void Analyze() 128 { 129 char str; 130 char letter[20]; 131 char num[20]; 132 char other[20]; 133 int i; 134 do 135 { 136 Q.front=Q.front->next; //获取单个字符 137 str=Q.front->ch; 138 if (isalpha(str)!=0) //如果是字符 139 { 140 i=-1; 141 while (isalnum(str)!=0) 142 { 143 letter[++i]=str; 144 Q.front=Q.front->next; 145 str=Q.front->ch; 146 } 147 letter[i+1]='