#includeiostream#includefstream#includeiomanip#includestringusingnamespacestd;#definestacksize10#definestringsize20typedefstructsqst//定义分析栈{intdata[stacksize];inttop;//栈顶指针}sqstack;stringword1[]={prgm,prgm',expr,term,expr',factor,term',system_goal};stringword2[]={#,;,+,*,(,),NUM};intmain(){voidout(sqstackst,stringstr,intsp,intk);//输出函数voidinit(intYy_pushtab[13][4],intYy_d[264][7]);//初始化分析栈Yy_d[]与Yy_pushtab[]voidstr_to_st1(stringstr,intst1[]);//对输入字符串的转换voidForeparser(sqstackst,intYy_pushtab[13][4],intYy_d[264][7],intst1[],stringstr);//预测分析法intYy_pushtab[13][4],Yy_d[264][7];intst1[stringsize];stringstr;sqstackst;st.top=-1;//分析栈的初始化st.top++;st.data[st.top]=263;//分析栈初始化#cout请输入字符串:;cinstr;cout栈(符号)栈(数值)输入串What_to_doendl;str_to_st1(str,st1);init(Yy_pushtab,Yy_d);Foreparser(st,Yy_pushtab,Yy_d,st1,str);return0;}voidout(sqstackst,stringstr,intsp,intk)//输出函数{intn,m=0;for(inti=0;i=sp;i++)//输出栈(符号){if(st.data[i]7){coutword2[st.data[i]];n=word2[st.data[i]].length()+1;}else{coutword1[st.data[i]-256];n=word1[st.data[i]-256].length()+1;}m=n+m;}for(i=m;i30;i++)cout;for(i=0;i=sp;i++)//输出栈(数字)coutsetiosflags(ios::left)setw(3)st.data[i];for(inth=sp+1;h6;h++)cout;for(intj=k;jstrlen(str.c_str());j++)//输出输入串coutstr[j];for(intg=strlen(str.c_str())-k;g10;g++)cout;cout;}voidinit(intYy_pushtab[13][4],intYy_d[264][7])//初始化分析栈Yy_d[]与Yy_pushtab[]{inti,j;ifstreaminfile1(1.txt,ios::in);ifstreaminfile2(2.txt,ios::in);for(i=0;i13;i++){for(j=0;j4;j++){infile1Yy_pushtab[i][j];//coutYy_pushtab[i][j];}//coutendl;}for(i=256;i264;i++){for(j=0;j7;j++){infile2Yy_d[i][j];//coutYy_d[i][j];}//coutendl;}infile1.close();infile2.close();}voidstr_to_st1(stringstr,intst1[])//对输入字符串的转化{for(inti=0;istrlen(str.c_str());i++){switch(str[i]){case'(':st1[i]=4;break;case'+':st1[i]=2;break;case')':st1[i]=5;break;case';':st1[i]=1;break;case'*':st1[i]=3;break;case'#':st1[i]=0;break;default:st1[i]=7;}if(str[i]='0'&&str[i]='9')st1[i]=6;}}voidForeparser(sqstackst,intYy_pushtab[13][4],intYy_d[264][7],intst1[],stringstr)//预测分析法{inti,k=0,what_to_do;while(st.top!=-1){out(st,str,st.top,k);if(st.data[st.top]=0&&st.data[st.top]=6)//栈顶元素为终结符if(st.data[st.top]!=st1[k]){cout未能分析成功endl;break;}else{st.top--;k++;coutendl;}else{//栈顶元素为非终结符what_to_do=Yy_d[st.data[st.top]][st1[k]];coutwhat_to_doendl;//输出what_to_doif(what_to_do==-1){coutstr不是本文法句子。endl;break;}else{st.top--;for(i=0;i4;i++)//把Yy_pushtab[what_to_do]中列出的全部常数压入分析栈if(Yy_pushtab[what_to_do][i]!=-1&&Yy_pushtab[what_to_do][i]!=0){st.top++;st.data[st.top]=Yy_pushtab[what_to_do][i];}}}if(st.top==-1&&st1[k]==0)coutstr是本文法句子。endl;}}