资源描述:
《编译原理词法分析程序》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、#include#include#include#include#includeusingnamespacestd;ifstreamfp("source.txt",ios::in);charcbuffer;char*key[13]={"if","else","for","while","do","return","break","continue","int","void","main","const","printf"};
2、//关键字char*border[7]={",",";","{","}","(",")","//"};//分界符char*arithmetic[6]={"+","-","*","/","++","--"};//运算符char*relation[7]={"<","<=","=",">",">=","==","!="};//关系运算符char*lableconst[80];//标识符intconstnum=40;intlableconstnum=0;intlinenum=1;//统计常数和标识符数量intsearch(ch
3、arsearchchar[],intwordtype){inti=0,t=0;switch(wordtype){case1:{for(i=0;i<=12;i++)//关键字{if(strcmp(key[i],searchchar)==0)return(i+1);}return(0);}case2:{for(i=0;i<=6;i++)//分界符{if(strcmp(border[i],searchchar)==0)return(i+1);}return(0);}case3:{for(i=0;i<=5;i++)//运算符{
4、if(strcmp(arithmetic[i],searchchar)==0)return(i+1);}return(0);}case4:{for(i=0;i<=6;i++)//关系运算符{if(strcmp(relation[i],searchchar)==0)return(i+1);}return(0);}case5:{for(t=40;t<=constnum;t++)//常数{if(strcmp(searchchar,lableconst[t])==0)//判断该常数是否已出现过return(t+1);}labl
5、econst[t-1]=(char*)malloc(sizeof(searchchar));//为新的元素分配内存空间strcpy(lableconst[t-1],searchchar);//为数组赋值lableconst指针数组名constnum++;//常数个数自加return(t);}case6:{for(i=0;i<=lableconstnum;i++){if(strcmp(searchchar,lableconst[i])==0)//判断标识符是否已出现过return(i+1);}lableconst[i-1
6、]=(char*)malloc(sizeof(searchchar));strcpy(lableconst[i-1],searchchar);lableconstnum++;//标识符个数自加return(i);}default:cout<<"错误!";}}charalphaprocess(charbuffer)//字符处理过程{intatype;inti=-1;charalphatp[20];while((isalpha(buffer))
7、
8、(isdigit(buffer)))//这两个函数分别是判字符和判数字函数位
9、于ctype.h中{alphatp[++i]=buffer;fp.get(buffer);}alphatp[i+1]=' ';//在末尾添加字符串结束标志if(atype=search(alphatp,1))cout<<"linenum:"<10、"<<"标识符"<