资源描述:
《编译原理实验—词法分析器.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、编译原理实验—词法分析器代码:#include#include#include#include#includeusingnamespacestd;voidout1(inti,char*str){cout<<"("<='a'&&ch<='z')
2、
3、(c
4、h>='A'&&ch<='Z'))return1;elsereturn0;}intIsDigit(charch)//判断ch是否是数字{if(ch>='0'&&ch<='9')return1;elsereturn0;}intGetBC(charch)//判断ch是否是空格{if(ch=='')return1;elsereturn0;}charGetChar(char*str,inti)//返回字符串当前位置的字符{returnstr[i];}voidReserve(char*str)//判断字符串str是关键字还是标识符{charchar1[20][50];strcpy(cha
5、r1[1],"break");strcpy(char1[2],"char");strcpy(char1[3],"continue");strcpy(char1[4],"do");strcpy(char1[5],"double");strcpy(char1[6],"else");strcpy(char1[7],"extern");strcpy(char1[8],"float");strcpy(char1[9],"for");strcpy(char1[10],"int");strcpy(char1[11],"if");strcpy(char1[12],"long");strcpy(
6、char1[13],"short");strcpy(char1[14],"static");strcpy(char1[15],"switch");strcpy(char1[16],"void");strcpy(char1[17],"while");inti;intflag=0;for(i=1;i<18;i++){if(strcmp(str,char1[i])==0){flag=i;break;}}if(flag!=0&&str[0]!=0)out1(i,str);//输出关键字elseif(str[0]!=0)out1(70,str);//输出标识符}voidDTB(char*
7、str)//将str字符串的数字转换成二进制并输出{longsum;inti;ints[100];sum=atoi(str);//字符串转换成整形if(sum==0)out1(80,str);else{for(i=0;sum!=0;i++){s[i]=sum%2;sum=sum/2;}cout<<"("<<80<<",";for(i=i-1;i>=0;i--)cout<
8、中读得的一行字符charfilename[10];//文件名charch='';intj;inti=0;cout<<"请输入文件名:";cin>>filename;memset(str2,0,sizeof(str2));//置空字符串memset(str2,0,sizeof(str3));//置空str3字符串ifstreamfin1(filename);if(!fin1){cout<<"Cannotopenthefile.";//未找到对应文件名的文件exit(1);}while(fin1){fin1.getline(str3,1000);//读出一行字符串strcat(
9、str1,str3);//将文件中的所有字符合并成一个字符串}while(ch){if(IsLetter(ch)){j=0;str2[j++]=ch;ch=GetChar(str1,i++);while(!GetBC(ch)&&(IsLetter(ch)
10、
11、IsDigit(ch)))//字母后是数字或字母并且非空格时则继续向后扫描{if(!GetBC(ch))str2[j++]=ch;ch=GetChar(str1,i++);}Reserve(str2);memset(str2,0,size