词法分析程序

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

源代码:#includeiostream#includeiomanip#includefstream#includestringusingnamespacestd;#defineMAX50charch='';stringkeyword[50]={bool,break,case,include,char,const,continue,default,do,double,else,false,float,for,if,int,long,namespace,new,return,short,signed,struct,switch,true,using,void,while,then};intgjz(stringc){inti;for(i=0;iMAX;i++){if(keyword[i].compare(c)==0)return1;}return0;}intzm(charc){if(((c='z')&&(c='a'))||((c='Z')&&(c='A')))return1;elsereturn0;}intnum(charc){if(c='0'&&c='9')return1;elsereturn0;}voidcaculate(FILE*fpin){ofstreamout(mytest.txt,ios::out);stringarr=;while((ch=fgetc(fpin))!=EOF){arr=;if(ch==''||ch=='\t'||ch=='\n'){}elseif(zm(ch)){while(zm(ch)||num(ch)){arr=arr+ch;ch=fgetc(fpin);}fseek(fpin,-1L,SEEK_CUR);if(gjz(arr)){outarr\t1\t关键字endl;}elseoutarr\t2\t标识符endl;}elseif(num(ch)){while(num(ch)||ch=='.'&&num(fgetc(fpin))||fgetc(fpin)=='e'||ch=='e'){if(ch=='.')fseek(fpin,-1L,SEEK_CUR);arr=arr+ch;if(ch=='e'){ch=fgetc(fpin);if(ch=='+')arr+='+';else{arr+='-',fseek(fpin,-1L,SEEK_CUR);};}ch=fgetc(fpin);}fseek(fpin,-3L,SEEK_CUR);outarr\t3\t无符号数endl;}elseswitch(ch){case'+':case'-':case'*':case'=':case'/':outch\t4\t运算符endl;break;case'(':case')':case'[':case']':case';':case'#':case'.':case',':case'{':case'}':outch\t5\t界限符endl;break;case'':{stringstring1=;do{string1+=ch;ch=fgetc(fpin);}while(ch!='');string1+=ch;outstring1\t6\t字符串endl;}break;case':':{ch=fgetc(fpin);if(ch=='=')out:=\t4\t运算符endl;else{out=\t4\t运算符endl;;fseek(fpin,-1L,SEEK_CUR);}}break;case'':{ch=fgetc(fpin);if(ch=='=')out=\t4\t运算符endl;if(((ch='z')&&(ch='a'))||((ch='Z')&&(ch='A'))){fseek(fpin,-1L,SEEK_CUR);out\t5\t界限符endl;}elseif(ch=='')out\t7\t控制符endl;elseif(ch=='')out\t4\t运算符endl;else{out\t4\t运算符endl;fseek(fpin,-1L,SEEK_CUR);}}break;case'':{ch=fgetc(fpin);if(ch=='=')out=\t4\t运算符endl;if(ch=='')out\t7\t控制符endl;if(ch=='\n'){fseek(fpin,-1L,SEEK_CUR);out\t5\t界限符endl;}else{out\t4\t运算符endl;fseek(fpin,-1L,SEEK_CUR);}}break;default:outch\t无法识别字符endl;}}}voidread(){ifstreamin(mytest.txt,ios::out);stringx;while(in){inx;coutx'\t';inx;cout.width(20);coutx'\t';inx;cout.width(20);coutxendl;}}voidmain(){charin_fn[30];FILE*fpin;cout请输入源文件名(包括路径和后缀名):;for(;;){cinin_fn;if((fpin=fopen(in_fn,r))!=NULL)break;elsecout文件路径错误!请输入源文件名(包括路径和后缀名):;}cout\n********************词法分析工作如下*********************endl;caculate(fpin);fclose(fpin);coutendl;read();cout\n********************参看本目录下的mytest.txt*********************endl;system(pause);}

1 / 4
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功