资源描述:
《用c语言实现词法分析器》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、用C语言实现词法分析器#include#include#include#define_KEY_WORD_END"waitingforyourexpanding"typedefstruct{inttypenum;char*word;}WORD;charinput[255];chartoken[255]="";intp_input;intp_token;charch;char*rwtab[]={"main","if","then","while","do","static","int","double",
2、"struct","break","else","long","switch","case","typedef","char","return","const","float","short","continue","for","void","defult","sizeof","do","printf","include","scanf",_KEY_WORD_END};WORD*scaner();intmain(){intover=1;WORD*oneword=malloc(sizeof(WORD));printf("EnterYourwords(endwi
3、th$):");scanf("%[^$]s",input);p_input=0;printf("Yourwords:%s",input);while(over<1000&over!=-1){oneword=scaner();if(oneword->typenum<1000)printf("(%d,%s)",oneword->typenum,oneword->word);over=oneword->typenum;}//printf("press$toexit:");scanf("%[^$]s",input);system("pause");ret
4、urn0;}//**************************************************************************************************charm_getch(){ch=input[p_input];p_input=p_input+1;return(ch);}//得到字符voidgetbc(){while(ch==''
5、
6、ch==10){ch=input[p_input];p_input=p_input+1;}}//去空格voidconcat(){token[p_token]=ch;
7、p_token=p_token+1;token[p_token]=' ';}//连接单词intletter(){if(ch>='a'&&ch<='z'
8、
9、ch>='A'&&ch<='Z')return1;elsereturn0;}//判断字母intdigit(){if(ch>='0'&&ch<='9')return1;elsereturn0;}//判断数字intreserve(){inti=0;while(strcmp(rwtab[i],_KEY_WORD_END)){if(!strcmp(rwtab[i],token)){returni+1;}i++;}
10、return10;}//找关键字voidretract(){p_input=p_input-1;}//回退字符char*dtb(){}//********************************************************************************WORD*scaner(){WORD*myword=malloc(sizeof(WORD));myword->typenum=10;myword->word="";p_token=0;m_getch();getbc();if(letter()){while(lett
11、er()
12、
13、digit()){concat();m_getch();}retract();myword->typenum=reserve();myword->word=token;printf("");return(myword);}elseif(digit()){while(digit()){concat();m_getch();}retract();myword->typenum=20;myword->word=token;printf("");return(myword);}elseswitch(ch){case'=':m_getch();if
14、(ch=='='){myword->typenum=