aa.cpp
资源名称:cifa.rar [点击查看]
上传用户:dlqqsh
上传日期:2022-06-06
资源大小:1548k
文件大小:3k
源码类别:
词法分析
开发平台:
Visual C++
- # include <iostream>
- # include<string.h>
- //# include<stdio.h>
- //# include<ctype.h>
- //# include<conio.h>
- using namespace std;
- char pg[100],token[20]; //pg数组存放输入字符串,token为临时数组存放扫描时所读
- char ch;
- int syn,p,n,m,sum;
- char *rwtab[6]={"begin","if","then","while","do","end"};
- int scaner(char pg[]) //扫描函数
- {
- for(n=0;n<20;n++) token[n]=NULL;
- //int m,n,sum;
- ch=pg[p++];
- while(ch==' ')
- ch=pg[p++];
- if(ch>='a'&&ch<='z')
- {
- n=0;
- while((ch>='a'&&ch<='z')||(ch>='0'&&ch<='9'))
- {
- token[n++]=ch;
- ch=pg[p++];
- }
- token[n]=' ';
- syn=10;
- p--;
- for(m=0;m<6;m++)
- if(strcmp(token,rwtab[m])==0)
- {
- m++;
- syn=m;
- break;
- }
- }
- else
- if(ch>='0'&&ch<='9')
- {
- sum=0;
- while(ch>='0'&&ch<='9')
- {
- sum=sum*10+ch-'0';
- ch=pg[p++];
- }
- syn=11;
- p--;
- }
- else
- switch(ch)
- {
- case '<': m=0; token[m++]=ch;
- ch=pg[p++];
- if(ch=='>'){syn=21;token[m++]=ch;}
- else if(ch=='='){syn=22;token[m++]=ch;}
- else{syn=20;p--;}break;
- case '>': m=0; token[m++]=ch;
- ch=pg[p++];
- if(ch=='='){syn=24;token[m++]=ch;}
- else{syn=23;p--;}break;
- case ':': m=0; token[m++]=ch;
- ch=pg[p++];
- if(ch=='='){syn=18;token[m++]=ch;}
- else{syn=17;p--;}break;
- case '/': m=0; token[m++]=ch;
- ch=pg[p++];
- if(ch=='*')
- {
- do
- {
- token[m++]=ch;
- ch=pg[p++];
- }while(ch!='*');
- token[m++]=ch;
- ch=pg[p++];
- if(ch=='/') {token[m++]=ch;syn=-2;}
- }
- else{syn=16;p--;}break;
- case '+': syn=13;token[0]=ch;break;
- case '-': syn=14;token[0]=ch;break;
- case '*': syn=15;token[0]=ch;break;
- case '=': syn=25;token[0]=ch;break;
- case ';': syn=26;token[0]=ch;break;
- case '(': syn=27;token[0]=ch;break;
- case ')': syn=28;token[0]=ch;break;
- case '#': syn=0;token[0]=ch;break;
- default: syn=-1;
- }
- return syn;
- }
- void main()
- {
- p=0;
- while(1)
- {
- cout<<endl<<endl;
- printf( " please input string and end with #:n");
- do
- {
- pg[p]=ch=cin.get();
- p++;
- }while(ch!='#');
- p=0;
- do
- {
- syn=scaner(pg);
- switch(syn)
- {
- case 11: cout<<"("<<syn<<","<<sum<<")"<<endl;break;
- case -1: cout<<"你输入的字符无法识别请重新输入!"<<endl;break;
- case -2: cout<<"This is defination:"<<endl;cout<<token<<endl;break;
- default:
- /*int mm=strlen(token);
- //mm=strlen(token);
- if(mm==1&&(token[0]>='a'&&token[0]<='z'))
- {
- cout<<"("<<syn<<",'";
- cout<<token<<"')"<<endl;
- }
- else*/
- cout<<"("<<syn<<",";cout<<token<<")"<<endl;
- }
- }while(syn!=0);
- }
- }