1、 编译原理课程实验报告 实验题目: 某种简单程序语言的词法分析器的设计 与实现 专 业: 计算机科学与技术 班 级: 11060341 学 号: 11060341 姓 名: 实验目的:设计一个词法分析程序,理解词法分析器实现的原理,掌握程序设计语言中的各类单词的词法分析方法,加深对词法分析原理的理解。实验任务:词法分析是从左向右扫描每行源程序的符号,拼成单词,换成统一的二元式 (单词种别,单词符号的属性值)表示。对给定的程序通过词法分析器识别一个个单词符号,并以二元式(单词种别,单词符号的属性值)显示,本程序则是通过对给定程序段分析后以单词符号和文字提示显示)实验流程:程序清单:#includ
2、e#include#includeusing namespace std;int k=0;struct word char name10; int kind; word1000;char key3510= scanf,short,int,long,float,double,char,struct,union, printf,typedef,const,unsigned,signed,extern,register,static, volatile,void,if,else,switch,case,for,do,while,goto, continue,break,default,sizeof,
3、return,include,bool ;bool cmp(char a) int i; for(int k=0; k35; k+) if(strcmp(a,keyk)=0) return 1; return 0;int main() #ifdef LOCAL freopen(in.txt, r, stdin); freopen(out.txt, w, stdout); #endif int p,q,flag; char a1000,b10,ch; while(gets(a) p=0; int len=strlen(a); while(p=a&ch=A&ch=a&ch=A&ch=0&ch=0&
4、ch=0&ch=0&at=a&at=A&at=0&ch) p+; ch=ap; if(ch=|ch=) b0=; b1=ch; strcpy(wordk.name,b); wordk+.kind=5; ch=a+p; else b0=; strcpy(wordk.name,b); wordk+.kind=5; else if(ch=) p+; ch=ap; if(ch=|ch=) b0=; b1=ch; strcpy(wordk.name,b); wordk+.kind=5; ch=a+p; else b0=; strcpy(wordk.name,b); wordk+.kind=5; else
5、 if(ch=!) p+; ch=ap; if(ch=) b0=!; b1=; strcpy(wordk.name,b); wordk+.kind=5; ch=a+p; else b0=!; strcpy(wordk.name,b); wordk+.kind=5; else if(ch=&) p+; ch=ap; if(ch=&) b0=b1=&; strcpy(wordk.name,b); wordk+.kind=5; ch=a+p; else b0=&; strcpy(wordk.name,b); wordk+.kind=5; else if(ch=|) p+; ch=ap; if(ch=
6、|) b0=b1=|; strcpy(wordk.name,b); wordk+.kind=5; ch=a+p; else b0=|; strcpy(wordk.name,b); wordk+.kind=5; for(int i=0; ik; i+) switch(wordi.kind) case 1: printf(标识符,); break; case 2: printf(常量,); break; case 3: printf(关键字,); break; case 4: printf(界符,); break; case 5: printf(运算符,); break; printf(%s)n,wordi.name); int a1=0,a2=0,a3=0,a4=0,a5=0; for(int i=0;ik;i+) if(wordi.kind=1) a1+; else if(wordi.kind=2) a2+; else if(wordi.kind=3) a3+; else if(wordi.kind=4) a4+; else if(wordi.kind=5) a5+; printf(标识符:%dn常量:%dn关键字:%dn界符:%dn运算符:%dn,a1,a2,a3,a4,a5); return 0;运行结果: