资源描述:
《袁德的编译原理实验报告》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、实验一:词法分析程序的主要任务一实验目的熟悉了解词法分析二实验环境Windowsvcc++编程语言三实验内容1.读源程序,产生单词符号2.词法分析程序的其他任务:3.滤掉空格,跳过注释、换行符4.追踪换行标志,复制出错源程序,5.宏展开实验源代码如下:#include#include#include#include#includeusingnamespacestd;ifstreamfp("d:/source.txt",ios::in);//source.tx
2、t内容是代码本身charcbuffer;char*key[13]={"if","else","for","while","do","return","break","continue","int","void","main","const","printf"};//关键字char*border[7]={",",";","{","}","(",")","//"};//分界符char*arithmetic[6]={"+","-","*","/","++","--"};//运算符char*relation[7]={"<","<=","=",">",">=",
3、"==","!="};//关系运算符char*lableconst[80];//标识符intconstnum=40;intlableconstnum=0;intlinenum=1;//统计常数和标识符数量intsearch(charsearchchar[],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+
4、+)//分界符{if(strcmp(border[i],searchchar)==0)return(i+1);}return(0);}case3:{for(i=0;i<=5;i++)//运算符{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<=constnu
5、m;t++)//常数{if(strcmp(searchchar,lableconst[t])==0)//判断该常数是否已出现过return(t+1);}lableconst[t-1]=(char*)malloc(sizeof(searchchar));//为新的元素分配内存空间strcpy(lableconst[t-1],searchchar);//为数组赋值lableconst指针数组名constnum++;//常数个数自加return(t);}case6:{for(i=0;i<=lableconstnum;i++){if(strcmp(search
6、char,lableconst[i])==0)//判断标识符是否已出现过return(i+1);}lableconst[i-1]=(char*)malloc(sizeof(searchchar));strcpy(lableconst[i-1],searchchar);lableconstnum++;//标识符个数自加return(i);}default:cout<<"错误!";}}charalphaprocess(charbuffer)//字符处理过程{intatype;inti=-1;charalphatp[20];while((isalpha(bu
7、ffer))
8、
9、(isdigit(buffer)))//这两个函数分别是判字符和判数字函数位于ctype.h中{alphatp[++i]=buffer;fp.get(buffer);}alphatp[i+1]=' ';//在末尾添加字符串结束标志if(atype=search(alphatp,1))cout<<"linenum:"<10、<<"String="<