源代码如下:
#include<stdio.h>
#include<string.h>
#include<iostream>
char p[80],t[8];
char c;
int s,ps,m=0,n,row,sum=0;
char *r[100]={"begin","if","then","while","do","end"};
void fenxin()
{
for(n=0;n<8;n++) t[n]=NULL;
c=p[ps++];
while(c==' ')
{
c=p[ps];
ps++;
}
if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
{
m=0;
while((c>='0'&&c<='9')||(c>='a'&&c<='z')||(c>='A'&&c<='Z'))
{
t[m++]=c;
c=p[ps++];
}
t[m++]=' ';
ps--;
s=10;
for(n=0;n<6;n++) //将识别出来的字符和已定义的标示符作比较,
if(strcmp(t,r[n])==0)
{
s=n+1;
break;
}
}
else if((c>='0'&&c<='9')) //数字
{
{
sum=0;
while((c>='0'&&c<='9'))
{
sum=sum*10+c-'0';
c=[ps++];
}
}
ps--;
s=11;
if(sum>32767)
s=-1;
}
else switch(c)
{
case'<':m=0;t[m++]=c;
c=[ps++];
if(c=='>')
{
s=21;
t[m++]=c;
}
else if(c=='=')
{
s=22;
t[m++]=c;
}
else
{
s=23;
ps--;
}
break;
case'>':m=0;t[m++]=c;
c=p[ps++];
if(c=='=')
{
s=24;
t[m++]=c;
}
else
{
s=20;
ps--;
}
break;
case':':m=0;t[m++]=c;
c=p[ps++];
if(c=='=')
{
s=18;
t[m++]=c;
}
else
{
s=17;
p--;
}
break;
case'*':s=13;t[0]=ch;break;
case'/':s=14;t[0]=ch;break;
case'+':s=15;t[0]=ch;break;
case'-':s=16;t[0]=ch;break;
case'=':s=25;t[0]=ch;break;
case';':s=26;t[0]=ch;break;
case'(':s=27;t[0]=ch;break;
case')':s=28;t[0]=ch;break;
case'#':s=0;t[0]=ch;break;
case'
':s=-2;break;
default: s=-1;break;
}
}
int main()
{
p=0;
row=1;
cout<<"Please input string:"<<endl;
do
{
cin.get(c); p[ps++]=c;
}
while(c!='#');
ps=0;
do
{
fenxin();
switch(s)
{
case 11: cout<<"("<<s<<","<<sum<<")"<<endl; break;
case -1: cout<<"Error in row "<<row<<"!"<<endl; break;
case -2: row=row++;break;
default: cout<<"("<<s<<","<<t<<")"<<endl;break;
}
}
while (s!=0);
}
测试数据:
仍会报错,无法运行。
参考网站:https://wenku.baidu.com/view/f5c53ad1b4daa58da1114ae1.html
https://blog.csdn.net/cike110120/article/details/26555257