语法分析
#include<stdio.h>
#include<string.h>
#define N 800
main()
{
int j,i;
char a[N],b[20];
printf("请输入源程序:(以#结束)\n");
for(i=0;i<N;i++)
{
scanf("%c",&a[i]);
if(a[i]=='#')
break;
}
a[i+1]='\0';
i=0;
printf("识别出的种别码为:\n");
while(a[i]!='#')
{
if(a[i]>=65&&a[i]<=122)
{
j=0;
while((a[i]>=65&&a[i]<=122)||(a[i]>='0'&&a[i]<='9')||a[i]=='_')
{
b[j]=a[i];
j++;
i++;
}
i--;
b[j]='\0';
if(strcmp(b,"begin")==0) printf("<1,begin>\n");
else if(strcmp(b,"if")==0) printf("<2,if>\n");
else if(strcmp(b,"then")==0) printf("<3,then>\n");
else if(strcmp(b,"while")==0) printf("<4,while>\n");
else if(strcmp(b,"do")==0) printf("<5,do>\n");
else if(strcmp(b,"end")==0) printf("<6,end>\n");
else printf("<10,%s>\n",b);
}
else
{
switch(a[i])
{
case '+': printf("<13,+>\n");break;
case '-': printf("<14,->\n");break;
case '*': printf("<15,*>\n");break;
case '/': printf("<16,/>\n");break;
case ':':if(a[i+1]=='=')
{
printf("<18,:=>\n");
i++;
}
else printf("<17,:>\n");
break;
case '<': if(a[i+1]=='=')
{
printf("<21,<=>\n");
i++;
}
else if(a[i+1]=='>')
{
printf("<22,<>>\n");
i++;
}
else printf("<20,<>\n");
break;
case '>': if(a[i+1]=='=')
{
printf("<24,>=>\n");
i++;
}
else printf("<23,>>\n");
break;
case '=': printf("<25,=>\n");break;
case ';': printf("<26,;>\n");break;
case '(': printf("<27,(>\n");break;
case ')': printf("<28,)>\n");break;
case' ': break;
case'\n': break;
default:
if(a[i]>='0'&&a[i]<='9')
printf("<11,%c>\n",a[i]);
else
printf("'%c'输入错误!\n",a[i]);
break;
}
}
i++;
}
if(a[i]=='#') printf("<0,#>\n");
}