资源描述:
《c语言小子集的词法分析程序》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include#include#include#define_KEY_WORD_END"waitingfouyourexpanding"/*定义关键字的结束标志*/typedefstruct{inttypenum;/*种别码*/char*word;}WORD;charinput[255];/*源程序缓字符冲区*/chartoken[255]="";/*单词缓冲区*/intp_input;/*源程序字符指针*/intp_token;/*单词缓冲区指针*/charch;char*rwtab[]={"vo
2、id","int","float","char","if","else","while","do","return",_KEY_WORD_END};WORD*scaner();/*词法扫描函数,获得一个单词*/voidmain(){intover=1;intcount=0;WORD*oneword=newWORD;printf("EnterYourwords(endwith#):");scanf("%[^#]s",input);/*输入源程序字符串到缓冲区,以#结束*/p_input=0;printf("词法分析结果是:");while(over<1
3、000&&over!=-1){oneword=scaner();if(oneword->word=="OVER")break;elseif(oneword->typenum<1000)printf("(%d,%s)",oneword->typenum,oneword->word);over=oneword->typenum;count++;if(count%6==0)printf("");//每六行输出}}charm_getch()/*从输入源读一个字符到CH中*/{ch=input[p_input];p_input=p_input+1;returnch
4、;}voidgetbc()/*去掉空白字符*/{while(ch==''
5、
6、ch==10){ch=input[p_input];p_input=p_input+1;}}voidconcat()/*拼接单词*/{token[p_token]=ch;p_token=p_token+1;token[p_token]=' ';}intletter()/*判断是否是字母*/{if(ch>='a'&&ch<='z'
7、
8、ch>='A'&&ch<='Z')return1;elsereturn0;}intdigit()/*判断是否是数字*/{if(ch>='0'&&ch<=
9、'9')return1;elsereturn0;}intreserve()/*检索关键字表格*/{inti=1;while(strcmp(rwtab[i],_KEY_WORD_END)){if(!strcmp(rwtab[i],token)){returni+24;}i=i+1;}return1;}voidretract()/*回退一个字符*/{p_input=p_input-1;}char*dtb(){returnNULL;}WORD*scaner()/*词法扫描程序*/{inti=0;WORD*myword=newWORD;myword->typenum
10、=0;myword->word="";p_token=0;m_getch();getbc();if(letter()){while(letter()
11、
12、digit()){concat();m_getch();}retract();if(!strcmp(rwtab[i],token))myword->typenum=1;elsemyword->typenum=reserve();myword->word=token;returnmyword;}elseif(digit()){while(digit()){concat();m_getch();}retract(
13、);myword->typenum=2;myword->word=token;returnmyword;}elseswitch(ch){case'=':m_getch();if(ch=='='){myword->typenum=12;myword->word="==";returnmyword;}retract();myword->typenum=16;myword->word="=";returnmyword;break;case'+':myword->typenum=3;myword->word="+";returnmyword;break;case'-
14、':myword->typenum=4;myword