简单词法分析程序

来源:互联网 发布:gulp 压缩js css 编辑:程序博客网 时间:2024/05/21 06:38


/**************************************************///保留字符表 "begin","if","then","while","do","end",可自己添加修改 #include<stdio.h>#include<string.h>#include<iostream.h>#define N 100#define M 10char shuru[N],huoqu[M]={0};char ch;int Chooise,p,sum=0;char *key[6]={"begin","if","then","while","do","end"};    //保留字符表 void scaner(){int i;for(i=0;i<M;i++)      // huoqu数组清空       huoqu[i]=NULL;ch=shuru[p++];while(ch==' '){ch=shuru[p];p++;}int m=0;if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')){m=0;while((ch>='0'&&ch<='9')||(ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))    //获取一个标示符{huoqu[m++]=ch;ch=shuru[p++];}huoqu[m++]='\0';p--;Chooise=1;for(i=0;i<6;i++)                //判断是否为保留字符if(strcmp(huoqu,key[i])==0){Chooise=3;break;}}else if((ch>='0'&&ch<='9'))          //判断是否为数字常量{{sum=0;while((ch>='0'&&ch<='9')){sum=sum*10+ch-'0';ch=shuru[p++];}}p--;Chooise=2;if(sum>32767)Chooise=-1;}else switch(ch)                    //判断是否为运算符、分隔符{case'<':m=0;huoqu[m++]=ch;ch=shuru[p++];if(ch=='>'){Chooise=4;huoqu[m++]=ch;}else if(ch=='='){Chooise=4;huoqu[m++]=ch;}else{Chooise=4;p--;}break;case'>':m=0;huoqu[m++]=ch;ch=shuru[p++];if(ch=='='){Chooise=4;huoqu[m++]=ch;}else{Chooise=4;p--;}break;case':':m=0;huoqu[m++]=ch;ch=shuru[p++];if(ch=='='){Chooise=4;huoqu[m++]=ch;}else{Chooise=4;p--;}break;case'*':Chooise=4;huoqu[0]=ch;break;case'/':Chooise=4;huoqu[0]=ch;break;case'+':Chooise=4;huoqu[0]=ch;break;case'-':Chooise=4;huoqu[0]=ch;break;case'=':Chooise=4;huoqu[0]=ch;break;case';':                                          //判断是否为界符Chooise=5;huoqu[0]=ch;break;case'(':Chooise=5;huoqu[0]=ch;break;case')':Chooise=5;huoqu[0]=ch;break;case'#':Chooise=0;huoqu[0]=ch;break;case'\n':Chooise=-2;break;default: Chooise=-1;break;}}void main(){p=0;int row=1;                            //错误计数器cout<<"Please input string:(end of #)"<<endl;do                                    //输入 {cin.get(ch);shuru[p++]=ch;}while(ch!='#');p=0;cout<<"标示符1,常数2,关键字3,运算符4,界符5"<<endl;do{scaner();switch(Chooise){case 2:              cout<<"("<<Chooise<<","<<sum<<")"<<endl;   break;      case -1:              cout<<"Error in row "<<row<<"!"<<endl;   break;case -2:              row=row++;  break;        default:             cout<<"("<<Chooise<<","<<huoqu<<")"<<endl; break;}}while (Chooise!=0);}

实验结果:

0 0
原创粉丝点击