资源描述:
《【精品】编译原理词法分析》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、单词符号种别码单词符号种别码begin1■•17if2■■18then3<20while4<>21do5<=22end6>231etter(letter
2、digit)*10>二24digitdigit*11二25+13■26—14(27*15)28/16#0#include#includeusingnamespacestd;charprog[80];/*存放源程序的字符串*/intp;chartoken[8];/*存放的单词自身字符串*/intm;char*keytab[6]={,lnt^,4f^,,then^,,
3、while^,,doHendn};/*存放关键字的数组*/intn;charch;/*当前读到的字符*/intsyn;/*种别码*/intsum;//整型常数scaner();voidmain(){p=o;cout«'!pleaseinputastring(endwith'#,):n«endl;do{cin.get(ch);prog[p++]=ch;/*存放源程序的字符串*/}while(ch!=#);P=o;cout«nrusults:n«endl;do{scaner();switch(syn){case11:cout«sum«endl;brea
4、k;case-l:cout«nyouhaveinputawrongstringn«endl;exit(O);default:cout«token«endl;break;}}while(syn!=O);}scaner()//定义函数scaner{sum=0;for(m=O;m<8;m++)token[m++]=NULL;m=O;ch=prog[p];P++;while((ch==f,)
5、
6、(ch==,'))ch=prog[p++];//下一个if(((ch<=,z,)&&(ch>=,a,))ll((ch<=,Z,)&&(ch>=,A,))){whi
7、le(((ch<=,z,)&&(ch>=,a,))ll((ch<=,Z,)&&(ch>=,A,))ll((ch>=O)&&(chv=9))){token[m++]=ch;ch=prog[p++];P-;syn=10;〃表示字母或数字letter(letterldigit)*for(n=0;n<6;n++)if(strcmp(token,keytab[n])==0)//字符串的比较{syn=n+l;break;}}elseif((ch>=,0,)&&(chv=9)){while((ch>=,0,)&&(chv=9)){sum=sum*10+ch-,0,
8、;ch=prog[p++];}P-;syn=ll;//表示数字}elseswitch(ch){case‘V’:token[m++]=ch;ch=prog[p++];if(ch==,=,)syn=22;token[m++]=ch;〃表示v=}else{syn=20;P-;}break;case*>*:token[m++]=ch;ch=prog[p++];if(ch==,=,){syn=24;token[m++]=ch;〃表示>=}else{syn=23;P-;}break;casetoken[m++]=ch;ch=prog[p++];if(ch==,+
9、,){syn=17;//表示':'token[m++]=ch;}else{syn=13;〃表示P-S}break;caseL,:token[m++]=ch;ch=prog[p++];if(ch=〔'){syn=29;token[m++]=ch;}elseP-;break;case,!,:ch=prog[p++];if(ch=』){syn=21;token[m++]=ch;}else{syn=31;P-;}break;case=':token[m++]=ch;ch=prog[p++];if(ch===,){syn=25;token[m++]=ch;}e
10、lseP-;}break;casesyn=15;token[m++]=ch;break;case7':syn=16;token[m++]=ch;break;casesyn=27;token[m++]=ch;break;casesyn=28;token[m++]=ch;break;casesyn=5;token[m++]=ch;break;casesyn=6;token[m++]=ch;break;casesyn=26;token[m++]=ch;caseV:syn=28;token[m++]=ch;break;caseV*:syn=30;token[
11、m++]=ch;break;case#:syn=O;token[m++]=ch;break;case':':