#include<stdio.h>
#include<string.h>
char input[200];//存放输入字符串
char token[5];//存放构成单词符号的字符串
char ch; //存放当前读入字符
int p; //input[]下标
int fg; //switch标记
int num; //存放整形值
//二维字符数组,存放关键字
char index[6][6]={"begin","if","then","while","do","end"};
main()
{
p=0;
printf("please intput string(End with '#'):
");
do
{
ch=getchar();
input[p++]=ch;
}while(ch!='#');
p=0;
do
{
scaner();
switch(fg)
{
case 11:printf("( %d,%d ) ",fg,num);break;
case -1:printf("input error
"); break;
default:printf("( %d,%s ) ",fg,token);
}
}while(fg!=0);
getch(); //用于让程序停留在显示页面
}
/*词法扫描程序:*/
scaner()
{
int m=0;//token[]下标
int n;
//清空token[]
for(n=0;n<5;n++)
token[n]=NULL;
//获取第一个不为0字符
ch=input[p++];
while(ch==' ')ch=input[p++];
//关键字(标识符)处理流程
if((ch<='z'&&ch>='a')||(ch<='Z'&&ch>='A'))
{
while((ch<='z'&&ch>='a')||(ch<='Z'&&ch>='A')||(ch<='9'&&ch>='0'))
{
token[m++]=ch;
ch=input[p++];
}
token[m++]=' ';
ch=input[--p];
fg=10;
for(n=0;n<6;n++)
if(strcmp(token,index[n])==0)//strcmp()比较两个字符串,相等返回0
{
fg=n+1;
break;
}
}
//数字处理流程
else if((ch<='9'&&ch>='0'))
{
num=0;
while((ch<='9'&&ch>='0'))
{
num=num*10+ch-'0';
ch=input[p++];
}
ch=input[--p];
fg=11;
}
//运算符界符处理流程
else
switch(ch)
{
case '<':
m=0;
token[m++]=ch;
ch=input[p++];
if(ch=='>') //产生<>
{
fg=21;
token[m++]=ch;
}
else if(ch=='=') //产生<=
{
fg=22;
token[m++]=ch;
}
else
{
fg=20;
ch=input[--p];
}
break;
case '>':
token[m++]=ch;
ch=input[p++];
if(ch=='=') //产生>=
{
fg=24;
token[m++]=ch;
}
else //产生>
{
fg=23;
ch=input[--p];
}
break;
case ':':
token[m++]=ch;
ch=input[p++];
if(ch=='=') //产生:=
{
fg=18;
token[m++]=ch;
}
else //产生:
{
fg=17;
ch=input[--p];
}
break;
case '+':fg=13;token[0]=ch;break;
case '-':fg=14;token[0]=ch;break;
case '*':fg=15;token[0]=ch;break;
case '/':fg=16;token[0]=ch;break;
case ':=':fg=18;token[0]=ch;break;
case '<>':fg=21;token[0]=ch;break;
case '<=':fg=22;token[0]=ch;break;
case '>=':fg=24;token[0]=ch;break;
case '=':fg=25;token[0]=ch;break;
case ';':fg=26;token[0]=ch;break;
case '(':fg=27;token[0]=ch;break;
case ')':fg=28;token[0]=ch;break;
case '#':fg=0;token[0]=ch;break;
default:fg=-1;
}
}