编译原理词法分析器实验报告(共6页).doc
精选优质文档-倾情为你奉上编 译 原 理实验报告 词法分析器 院系: 班级: 姓名: 学号:词法分析器实验报告一、实验目的:设计一个词法分析程序,理解词法分析器实现的原理,掌握程序设计语言中的各类单词的词法分析方法,加深对词法分析原理的理解。二、实验原理:词法分析是从左向右扫描每行源程序的符号,拼成单词,换成统一的二元式 (单词种别码,单词符号的属性值)表示。对给定的程序通过词法分析器识别一个个单词符号,并以二元式(单词种别码,单词符号的属性值)显示,本程序则是通过对给定路径的文件的分析后以单词符号和文字提示显示)三、实验说明:(1)关键字:"begin","end","if","then","else","while","write","read","do", "call","const","char","until","procedure","repeat"(2)运算符:"+","-","*","/","="(3)界符:"","","","","",",",".","(",")",":"(4)其他标记 如字符串,表示以字母开头的标识符(5)空格、回车、换行符跳过(6)运行结果在屏幕上以如下格式显示:1 $无符号整数begin $关键字 if $关键字 + $运算符 ; $界符 a $普通标识符 /“$“为美元符号,不是大写字母S 测试功能时,可以多次设置包含不同字符,关键字的待解析文件,但要保证输入文件和后缀名时准确无误,仔细察看运行结果,检测该分析器的分析结果是否正确四、源代码:#include <iostream>#include<string>using namespace std;#define MAX 22 char ch =' 'string key15="begin","end","if","then","else","while","write","read","do", "call","const","char","until","procedure","repeat"int Iskey(string c) /关键字判断 int i; for(i=0;i<MAX;i+) if(keyi.compare(c)=0) return 1; return 0;int IsLetter(char c) /判断是否为字母 if(c<='z')&&(c>='a')|(c<='Z')&&(c>='A') return 1; else return 0;int IsDigit(char c) /判断是否为数字 if(c>='0'&&c<='9') return 1; else return 0;void analyse(FILE *fpin) string arr="" while(ch=fgetc(fpin)!=EOF) arr="" if(ch=' '|ch='t'|ch='n') else if(IsLetter(ch) while(IsLetter(ch)|IsDigit(ch) if(ch<='Z')&&(ch>='A') ch=ch+32; arr=arr+ch; ch=fgetc(fpin); fseek(fpin,-1L,SEEK_CUR); if (Iskey(arr)cout<<arr<<"t$关键字"<<endl; else cout<<arr<<"t$普通标识符"<<endl; else if(IsDigit(ch) while(IsDigit(ch)|ch='.'&&IsDigit(fgetc(fpin) arr=arr+ch; ch=fgetc(fpin); fseek(fpin,-1L,SEEK_CUR); cout<<arr<<"t$无符号实数"<<endl; else switch(ch) case'+': case'-' : case'*' : case'=' : case'/' :cout<<ch<<"t$运算符"<<endl;break; case'(' : case')' : case'' : case'' : case'' : case'.' : case',' : case'' : case'' :cout<<ch<<"t$界符"<<endl;break; case':' :ch=fgetc(fpin); if(ch='=') cout<<":="<<"t$运算符"<<endl; else cout<<"="<<"t$运算符"<<endl; fseek(fpin,-1L,SEEK_CUR); break;case'>' :ch=fgetc(fpin); if(ch='=') cout<<">="<<"t$运算符"<<endl; if(ch='>')cout<<">>"<<"t$输入控制符"<<endl; else cout<<">"<<"t$运算符"<<endl; fseek(fpin,-1L,SEEK_CUR); break; case'<' :ch=fgetc(fpin); if(ch='=')cout<<"<="<<"t$运算符"<<endl; else if(ch='<')cout<<"<<"<<"t$输出控制符"<<endl; else if(ch='>') cout<<"<>"<<"t$运算符"<<endl; elsecout<<"<"<<"t$运算符"<<endl; fseek(fpin,-1L,SEEK_CUR); break; default : cout<<ch<<"t$无法识别字符"<<endl; void main() char in_fn30; FILE * fpin; cout<<"请输入源文件名(包括路径和后缀名):" for(;) cin>>in_fn; if(fpin=fopen(in_fn,"r")!=NULL) break; else cout<<"文件路径错误!请输入源文件名(包括路径和后缀名):" cout<<"n*分析如下*"<<endl; analyse(fpin); fclose(fpin); cout<<endl; cout<<"按任意键结束"<<endl; int a; cin>>a;运行结果截图:输入:输出: 生成的单词表目标文件:专心-专注-专业