/*
begin if then while do end
:= + - * / < <= <> > >= = ; ( ) #
输入:所给文法的源程序字符串。
输出:二元组(syn,token或sum)构成的序列。
其中:syn为单词种别码;
token为存放的单词自身字符串;
sum为整型常数。
*/
#include
#include
char prog[80];
char token[8];
char ch;
int syn,p,m=0,n,sum=0; /* p是缓冲区prog的指针,m是token的指针*/
char *rwtab[6]={"begin","if","then","while","do","end"};
/*
char prog[]="begin if then 2>3 end#";
*/
void scaner();
int strcmpo(char a[],char b[]);
void print(char a[]);
int main()
{
p=0;
printf("please input string: \n");
do{ch=getchar();
prog[p]=ch;
p++;
}while(ch!='#');
p=0;
do
{
scaner();
switch(syn)
{ case 11: printf("(11,%d)\n",sum); break;
case -1: print(token);printf("-error!\n"); break;
default: printf("(%d,",syn);
print(token);
printf(")\n");
}
}while (syn!=0);
return 0;
}/*end of main()*/
void scaner()
{
for(n=0;n<8;n++) token[n]='\0';
ch=prog[p];
p++;
while(ch==' '||ch=='\n')
/*接收空格*/
{
ch=prog[p];
p++;
}
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
/*标志符和关键字ID=letter(letter| digit)* */
{
m=0;
while((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z')||(ch>='0'&&ch<='9'))
/*识别标志符*/
{
token[m]=ch;
m++;
ch=prog[p];
p++;
}
token[m]='\0';
p--;
syn=10;
for(n=0;n<6;n++)
/*识别关键字*/
{
if(strcmpo(token,rwtab[n])==0)
{
syn=n+1;
break;
}
}
}/*end of if*/
else if(ch>='0'&&ch<='9')
/*数字NUM=digit digit **/
{
sum=0;
while(ch>='0'&&ch<='9')
{
sum=sum*10+(int)ch-(int)'0';
ch=prog[p];
p++;
}
if(ch=='.')
{
ch=prog[p];
p++;
int i=1;
while(ch>='0'&&ch<='9')
{
sum+=((int)ch-(int)'0')*pow(0.1,i);
ch=prog[p];
p++;
i++;
}
}
p--;
syn=11;
}/*end of else if*/
else
/*识别运算符和界符*/
switch(ch)
{
case'<':m=0;
token[m]=ch;
ch=prog[p];
p++;
if(ch=='>'){syn=21;m++;token[m]=ch;}
else if(ch=='='){syn=22;m++;token[m]=ch;}
else{p--;syn=20;}
m++;
token[m]='\0';
break;
case'>':m=0;
token[m]=ch;
ch=prog[p];
p++;
if(ch=='='){syn=24;m++;token[m]=ch;}
else{syn=23;p--;}
m++;
token[m]='\0';
break;
case':':m=0;
token[m]=ch;
ch=prog[p];
p++;
if(ch=='='){syn=18;m++;token[m]=ch;}
else{syn=17;p--;}
m++;
token[m]='\0';
break;
case'+':syn=13;
token[0]=ch;
token[1]='\0';
break;
case'-':syn=14;
token[0]=ch;
token[1]='\0';
break;
case'*':syn=15;
token[0]=ch;
token[1]='\0';
break;
case'/':syn=16;
token[0]=ch;
token[1]='\0';
break;
case'=':syn=25;
token[0]=ch;
token[1]='\0';
break;
case';':syn=26;
token[0]=ch;
token[1]='\0';
break;
case'(':syn=27;
token[0]=ch;
token[1]='\0';
break;
case')':syn=28;
token[0]=ch;
token[1]='\0';
break;
case'#':syn=0;
token[0]=ch;
token[1]='\0';
break;
default:syn=-1;
token[0]=ch;
token[1]='\0';
}/*end of switch*/
}/*end of scaner*/
int strcmpo(char a[],char b[])
/*比较两字符串是否相同*/
{
int t=0;
while((a[t]!='\0')&&(b[t]!='\0')&&(a[t]==b[t]))t++;
if((a[t]=='\0')&&(b[t]=='\0'))return 0;
else return 1;
}/*end of strcmp*/
void print(char a[])
/*输出字符数组*/
{
int t=0;
while(a[t]!='\0')
{
printf("%c",a[t]);
t++;
}
}/*end of print*/