0917词法分析
#include<stdio.h>
#include<string.h>//strcmp()用于比较两个字符串,若str1==str2,则返回零;若str1>str2,则返回正数;若str1<str2,则返回负数
#include<conio.h>//getch()
#define max 200
char pro[max], lin[20];
int n,i,syn;
char *word[6]={ "begin", "if" , "then", "while", "do" ,"end" }; // 关键字,特殊标识符
char ch ;
scaner( )
{
int j=0;
for ( n=0; n<20; n++ )
lin[n]=NULL; //临时数组初始化
ch=pro[i++]; //读取字符串
while (ch==' ') //判断,跳过空字符
ch=pro[i++]; //读取整个单词
if ((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')||(ch>=48&&ch<=57)) //判断是否是字母或数字
{
if((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')) //判断标示符和特殊关键字
{
lin[j++]=ch;
ch=pro[i++]; //pro[i++]空,关键字
while((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')||(ch>=48&&ch<=57))//判断标识符
{
lin[j++]=ch;
ch=pro[i++];
}
lin[j]='\0'; //结束标志,回车
i--;
syn=10; //单词种别码
for (n=0;n<6 ;n++ )
if(strcmp(lin,word[n])==0) //查找关键字表是否符合
{
syn=n+1;
break ;
}
}
else //判断数字
{
while (ch>=48&&ch<=57)
{
lin[j++]=ch;
ch=pro[i++];
}
i--;
lin[j]='\0';
syn=11;
}
}
else //判断其它符号
{
//判断<,<=,<>
if(ch=='<')
{
lin[j++]=ch;
ch=pro[i++];
if (ch=='>')
{
syn=21;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch=='=')
{
syn=22;
lin[j++]=ch;
lin[j]='\0';
}
else
{
syn=20;
lin[j]='\0';
i--;
}
}
///判断>,>=
else if(ch=='>')
{
lin[j++]=ch;
ch=pro[i++];
if (ch=='=')
{
syn=24;
lin[j++]=ch;
lin[j]='\0';
}
else
{
syn=23;
lin[j]='\0';
i--;
}
}
//判断 :,:=
else if(ch==':')
{
lin[j++]=ch;
ch=pro[i++];
if (ch=='=')
{
syn=18;
lin[j++]=ch;
lin[j]='\0';
}
else
{
syn=17;
lin[j]='\0';
i--;
}
}
///判断其它符号
else if(ch=='+')
{
syn=13;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch=='-')
{
syn=14;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch=='*')
{
syn=15;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch=='/')
{
syn=16;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch=='=')
{
syn=25;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch==';')
{
syn=26;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch=='(')
{
syn=27;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch==')')
{
syn=28;
lin[j++]=ch;
lin[j]='\0';
}
else if(ch=='#')
{
syn=0;
lin[j++]=ch;
lin[j]='\0';
}
else
syn=-1;
}
return syn;
}
void main()
{
int i=0 ;
printf( "Please input source code:\n" );
do{
ch=getchar();//读入字符串
pro[i++]=ch;
}while(ch!='#');//将所读字符串存入数组pro[],直到遇到#
i=0;
do
{
scaner();
switch(syn)
{
case 11: printf ("(%d,%s)\n",syn,lin);
break;
case -1: printf("错误符号\n");
break;
default: printf ("(%d,%s)\n",syn,lin);
}
} while (syn!=0);
getch();
}