代碼
#include<iostream>
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
char A[20]; /*分析棧*/
char B[20]; /*剩餘串*/
char v1[20]={'i','+','*','(',')','#'};/*終結符*/
char v2[20]={'E','G','T','S','F'}; /*非終結符*/
int j=0,b=0,top=0,l; /*L爲輸入串長度*/
class type /*產生式類型定義*/
{
public:
char origin; /*大寫字符*/
char array[5]; /*產生式右邊字符*/
int length; /*字符個數*/
};
type e,t,g,g1,s,s1,f,f1; /*類對象*/
type C[10][10];/*預測分析表*/
void print() /*輸出分析棧*/
{
int a;
for(a=0;a<=top+1;a++)
cout<<A[a];
cout<<"\t\t";
}
void print1() /*輸出剩餘串*/
{
int j;
for(j=0;j<b;j++) /*輸出對齊符*/
cout<<" ";
for(j=b;j<=l;j++)
cout<<B[j];
cout<<"\t\t\t";
}
int main()
{
int m,n,k=0,flag=0,finish=0;
char ch,x;
type cha; /*用來接受C[m][n]*/
/*把文法產生式賦值結構體*/
e.origin='E';
strcpy(e.array,"TG");
e.length=2;
t.origin='T';
strcpy(t.array,"FS");
t.length=2;
g.origin='G';
strcpy(g.array,"+TG");
g.length=3;
g1.origin='G';
g1.array[0]='^';
g1.length=1;
s.origin='S';
strcpy(s.array,"*FS");
s.length=3;
s1.origin='S';
s1.array[0]='^';
s1.length=1;
f.origin='F';
strcpy(f.array,"(E)");
f.length=3;
f1.origin='F';
f1.array[0]='i';
f1.length=1;
for(m=0;m<=4;m++) /*初始化分析表*/
for(n=0;n<=5;n++)
C[m][n].origin='N'; /*全部賦爲空*/
/*填充分析表*/
C[0][0]=e;C[0][3]=e;
C[1][1]=g;C[1][4]=g1;C[1][5]=g1;
C[2][0]=t;C[2][3]=t;
C[3][1]=s1;C[3][2]=s;C[3][4]=C[3][5]=s1;
C[4][0]=f1;C[4][3]=f;
cout<<"提 示 : 本程序只能對由'i','+','*','(',')'構成的以'#'結束的字符串進行分析,"<<endl;
cout<<"請 輸入要分析的字符串:";
do/*讀入分析串*/
{
cin>>ch;
if ((ch!='i') &&(ch!='+') &&(ch!='*')&&(ch!='(')&&(ch!=')')&&(ch!='#'))
{
cout<<"輸入串中有非法字符\n";
exit(1); //強制退出程序
}
B[j]=ch;
j++;
}while(ch!='#');
l=j;/*分析串長度*/
ch=B[0];/*當前分析字符*/
A[top]='#'; A[++top]='E';/*'#','E'進棧*/
cout<<"步 驟 \t\t分析棧 \t\t剩餘字符 \t\t所用產生式"<<endl;
do
{
x=A[top--];/*x爲當前棧頂字符*/
cout<<k++;
cout<<"\t\t";
for(j=0;j<=5;j++)/*判斷是否爲終結符*/
if(x==v1[j])
{
flag=1;
break;
}
if(flag==1)/*如果是終結符*/
{
if(x=='#')
{
finish=1;/*結束標記*/
cout<<"acc!"<<endl;/*接受*/
getchar();
getchar();
exit(1);
//退出程序
}/*if*/
if(x==ch)
{
print();
print1();
cout<<"匹 配"<<ch<<endl;
ch=B[++b];/*下一個輸入字符*/
flag=0;/*恢復標記*/
}
else/*出錯處理*/
{
print();
print1();
cout<<"出 錯"<<ch<<endl;/*輸出出錯終結符*/
exit(1);
}
}
else/*非終結符處理*/
{
for(j=0;j<=4;j++)
if(x==v2[j])
{
m=j;/*行號*/
break;
}
for(j=0;j<=5;j++)
if(ch==v1[j]) {
n=j;/*列號*/
break;
}
cha=C[m][n];
if(cha.origin!='N')/*判斷是否爲空*/
{
print();
print1();
cout<<cha.origin<<"->";/*輸出產生式*/
for(j=0;j<cha.length;j++)
cout<<cha.array[j];
cout<<"\n";
for(j=(cha.length-1);j>=0;j--)
/*產生式逆序入棧*/
A[++top]=cha.array[j];
if(A[top]=='^')/*爲空則不進棧*/
top--;
}
else/*出錯處理*/
{
print();
print1();
cout<<"出 錯"<<x;/*輸出出錯非終結符*/
exit(1);
}
}
}while(finish==0);
return 0;
}