1、学 生 实 验 报 告学 院: 软件与通信工程学院 课程名称: 编译原理 专业班级: 姓 名: 学 号: 学生实验报告学生姓名学号同组人实验项目C+实现词法分析器必修 选修 演示性实验 验证性实验 操作性实验 综合性实验实验地点实验仪器台号指导教师实验日期及节次周二上午 周三下午一、实验综述1、实验目的及要求使用任意语言实现词法分析器2、实验仪器、设备或软件Visual C+。二、实验过程(实验步骤、记录、数据、分析)代码:#include#include#includeusing namespace std;#define MAX 10 /保留字个数#define LIST_MAX_LENG
2、TH 10char ch= ; /存放最新读进的字符char strTokenLIST_MAX_LENGTH; /单词符号长度int len=0;/单词符号的长度int s=0; /判断是否多读一位char key3010=if,else,for,while,do,bool,int,char,double,friend,class,struct,return,delete,new,public,private,endl,break,const,static,include,endl,auto,iostream,cstring,define,void,cin,cout;char GetChar(
3、) /读一个字符ch=getchar();if(ch!=/n)return ch;return ;char GetBC() /检查ch是否为空白while(ch= )ch=GetChar();return ch;void Concat() /连接strTokenlen=ch;len+;int Reserve(char strToken) /判断是否为保留字for(int i=0;i(sizeof(key)/sizeof(key0);i+)if(strcmp(keyi,strToken)=0)return 1;return 0;int IsLetter() /判断是否为字母if(ch=a)|(c
4、h=A) return 1;else return 0;int IsDigit() /判断是否为数字 if(ch=0&ch=9) return 1; else return 0; void InsertId() /插入符号表ofstream outfile(symbol.txt,ios:app);for(int i=0;ilen;i+)outfilestrTokeni;outfileendl;outfile.close();void InsertConst() /插入常数表 ofstream outfile(number.txt,ios:app);for(int i=0;ilen;i+)out
5、filestrTokeni;outfileendl;outfile.close();int main()cout请输入字符串代码:endl;if(s!=1)GetChar();while(ch!=10)/getchar();/coutchendl;GetBC();if(IsLetter()while(IsLetter()Concat();GetChar();s=1;/Retract();if(Reserve(strToken)coutstrToken$保留字endl;len=0;memset(strToken,0,sizeof(strToken); /清空数组elsecoutstrToken$
6、普通标识符endl;InsertId();len=0;memset(strToken,0,sizeof(strToken); else if(IsDigit()while(IsDigit()Concat();GetChar();s=1;/Retract();coutstrToken$常数endl;InsertConst();len=0;memset(strToken,0,sizeof(strToken);else if(ch=#) cout#$警号endl; s=0;else if(ch=;) cout;$分号endl; s=0;else if(ch=+) cout+$加号endl; s=0;
7、else if(ch=) cout=$等号endl; s=0;else if(ch=*) cout*$乘号endl; s=0;else if(ch=;) cout;$分号) cout$大于号endl; s=0;else if(ch=) cout$小于号endl; s=0;else if(ch=() cout($左括号endl; s=0;else if(ch=) cout)$右括号endl; s=0;else if(ch=) cout$左中括号endl; s=0;else if(ch=) cout$右中括号endl; s=0;else if(ch=) cout$双引号endl; s=0;else coutch错误处理endl;if(s!=1)GetChar();return 0;三、结论1、实验结果2、分析讨论 通过本次实验,使我更加了解了词法分析器的工作原理,并基本学会了怎样用程序代码去实现它。四、指导教师评语及成绩:评语: 成绩: 指导教师签名: 批阅日期: