算法分析原理
词法分析程序的功能:
用户输入一段程序,从左至右地对源程序进行扫描,按照语言的词法规则识别各类单词,并产生相应单词的属性字,分别将数字,变量,关键字等区分并输出对应的种别码。
已完成的代码:
#include<stdio.h>
void classify();
char ch;
char total[100];
int n,m,code,sum=0;
char *keyword[8]={"begin","if","then","while","do","end","l(l|d)*","dd*"};
char keyword2[8]={'\0'};
main()
{
printf("请输入您的程序:");
n=0;
do{
ch=getchar();
total[n]=ch;
n++;
}while(ch=='#');
n=0;
do{
classify();
if(code==10)
printf("它是变量或变量名(100,%s)",keyword2);
else
printf("它是关键字(%d,%s)",code,keyword2);
}while(code!=-1);
}
void classify()
{
int i;
ch=total[n];
n++;
m=0;
while(ch==' ')
{
ch=total[n];
n++;
}
while(ch=='#')
{
code=-1;
}
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>=0&&ch<=9))
while((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
{
keyword2[m]=ch;
m++;
ch=total[n];
n++;
}
keyword2[m]='\0';
code=10;
for(i=0;i<8;i++)
if(strcmp(keyword2,keyword[i])==0)
code=i+1;
else
if(ch=='+'||ch=='-'||ch=='*'||ch=='/')
switch(ch)
{
case '+': code=13;ch=total[n];
n++;break;
case '-': code=14;ch=total[n];
n++;break;
case '*': code=15;ch=total[n];
n++;break;
case '/': code=16;ch=total[n];
n++;break;
}
else if(ch==';'||ch=='('||ch==')')
switch(ch)
{
case ';': code=26;ch=total[n];
n++;break;
case '(': code=27;ch=total[n];
n++;break;
case ')': code=28;ch=total[n];
n++;break;
}
else
}