您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 市场营销 > PL0词法分析器代码
#includeiostream#includestdio.h#includestring.h#defineLINE100//源程序每行至多100个字符usingnamespacestd;charbuf[LINE];//按行存放字符intlength;//记录每行长度char*key[9]={PROGRAM,BEGIN,END,CONST,VAR,WHILE,DO,IF,THEN};//关键字char*ch[15]={+,-,*,/,:=,=,,,=,=,(,),;,,};//限定符/界符intreadfile(FILE*fp)//读取.txt文件,只读取一行{charch;//存放读取的单个字符length=0;ch=fgetc(fp);//调用函数fgetc()读取文件内容while(!feof(fp)&&ch!='\n')//读取字符到buf[]数组{buf[length]=ch;ch=fgetc(fp);length++;}if(length!=0)return1;elsereturn0;}voidlexical(char*buf,intlength)//词法分析函数{inti;charbuffer[LINE];for(i=0;ilength;i++){buffer[i]=*buf;buf++;}for(i=0;ilength;i++){//判断是否为“常数”if(buffer[i]=='0'||buffer[i]=='1'||buffer[i]=='2'||buffer[i]=='3'||buffer[i]=='4'||buffer[i]=='5'||buffer[i]=='6'||buffer[i]=='7'||buffer[i]=='8'||buffer[i]=='9'){cout常数buffer[i];while(1){i++;if(buffer[i]=='0'||buffer[i]=='1'||buffer[i]=='2'||buffer[i]=='3'||buffer[i]=='4'||buffer[i]=='5'||buffer[i]=='6'||buffer[i]=='7'||buffer[i]=='8'||buffer[i]=='9')coutbuffer[i];elsebreak;}coutendl;}//判断是否为“算符/界符”elseif(buffer[i]=='+'||buffer[i]=='-'||buffer[i]=='*'||buffer[i]=='/'||buffer[i]=='='||buffer[i]=='('||buffer[i]==')'||buffer[i]==';'||buffer[i]==',')cout算符/界符buffer[i]endl;//elseif(buffer[i]==''||buffer[i]==''){if(buffer[i+1]=='=')cout算符/界符buffer[i]buffer[i+1]endl;elsecout算符/界符buffer[i]endl;}elseif(buffer[i]==':'&&buffer[i+1]=='=')cout算符/界符buffer[i]buffer[i+1]endl;//判断是否为“关键字”或“标识符”elseif(buffer[i]='A'&&buffer[i]='Z'){chara1[]=PROGRAM;chara2[]=BEGIN;chara3[]=END;chara4[]=CONST;chara5[]=VAR;chara6[]=WHILE;chara7[]=DO;chara8[]=IF;chara9[]=THEN;chars1[20];for(intj=0;buffer[i]!='';i++,j++)//for(intj=0;buffer[i]=='_'||(buffer[i]='0'&&buffer[i]='9')||(buffer[i]='a'&&buffer[i]='z')||(buffer[i]='A'&&buffer[i]='Z');i++,j++)s1[j]=buffer[i];s1[j]='\0';if(!strcmp(s1,a1))cout关键字a1endl;elseif(!strcmp(s1,a2))cout关键字a2endl;elseif(!strcmp(s1,a3))cout关键字a3endl;elseif(!strcmp(s1,a4))cout关键字a4endl;elseif(!strcmp(s1,a5))cout关键字a5endl;elseif(!strcmp(s1,a6))cout关键字a6endl;elseif(!strcmp(s1,a7))cout关键字a7endl;elseif(!strcmp(s1,a8))cout关键字a8endl;elseif(!strcmp(s1,a9))cout关键字a9endl;elsecout标识符s1endl;i--;}elseif(buffer[i]='a'&&buffer[i]='z'){intj;chars1[20];for(j=0;buffer[i]=='_'||(buffer[i]='0'&&buffer[i]='9')||(buffer[i]='a'&&buffer[i]='z')||(buffer[i]='A'&&buffer[i]='Z');){s1[j]=buffer[i];i++;j++;}s1[j]='\0';cout标识符s1endl;i--;}}}intmain(){charsourcefile[20];//定义源文件cout请输入源文件名字:;cinsourcefile;FILE*fp;fp=fopen(sourcefile,r);//读文件if(fp){while(readfile(fp))//调用读文件函数lexical(buf,length);//调用词法分析函数fclose(fp);}elsecout没有找到源文件!endl;getchar();return0;}
本文标题:PL0词法分析器代码
链接地址:https://www.777doc.com/doc-2851087 .html