资源描述:
《编译原理实验----词法分析》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、实验一词法分析器设计【实验目的】1.熟悉词法分析的基本原理,词法分析的过程以及词法分析中要注意的问题。2.复习高级语言,进一步加强用高级语言来解决实际问题的能力。3.通过完成词法分析程序,了解词法分析的过程。【实验内容】用C语言编写一个PL/0词法分析器,为语法语义分析提供单词,使之能把输入的字符串形式的源程序分割成一个个单词符号传递给语法语义分析,并把分析结果(基本字,运算符,标识符,常数以及界符)输出。【实验步骤和要求】1.要求绘出词法分析过程的流程图。2.根据词法分析的目的以及内容,确定完成分析过程所需模块。3.写出每个模块的源代码。4.整理程序清单
2、及所得结果。//源程序如下:#include#include#include#include#include#defineNULL"abc"usingnamespacestd;ifstreamfp("d:\cifa.cpp",ios::in);charcch;char*key[12]={"if","else","for","while","do","return","break","continue","int","void","main","const"};
3、//基本字char*border[10]={",",";","{","}","(",")","[","]",""","""};//界符char*arithmetic[6]={"+","-","*","/","++","--"};//算术运算符char*relation[7]={"<","<=","=",">",">=","==","!="};//关系运算符char*lableconst[80];//标识符intconstnum=40;intlableconstnum=0;intsearch(charsearchchar[],intwordtype){int
4、i=0,t=0;switch(wordtype){case1:{for(i=0;i<=11;i++){if(strcmp(key[i],searchchar)==0)return(i+1);}return(0);}case2:{for(i=0;i<=9;i++){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);}ca
5、se4:{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);}lableconst[t-1]=(char*)malloc(sizeof(searchchar));strcpy(lableconst[t-1],searchchar);constnum++;return(t);}case6
6、:{for(i=0;i<=lableconstnum;i++){if(strcmp(searchchar,lableconst[i])==0)return(i+1);}lableconst[i-1]=(char*)malloc(sizeof(searchchar));strcpy(lableconst[i-1],searchchar);lableconstnum++;return(i);}default:cout<<"错误!";}}charalphaprocess(charch){intatype;inti=-1;charalphatp[20];while
7、((isalpha(ch))
8、
9、(isdigit(ch))){alphatp[++i]=ch;fp.get(ch);}alphatp[i+1]=' ';if(atype=search(alphatp,1))cout<10、type;while((isdigit(ch))){digittp