编译原理非递归预测分析法.docx
附:代码#include<iostream>#include<fstream>#include<iomanip>#include<string>using namespace std;#define stacksize 10#define stringsize 20typedef struct sqst /定义分析栈int datastacksize;int top; /栈顶指针sqstack;string word1="prgm","prgm'","expr","term","expr'","factor","term'","system_goal"string word2 ="#","","+","*","(",")","NUM"int main()void out(sqstack st,string str,int sp,int k); /输出函数void init(int Yy_pushtab134,int Yy_d2647); /初始化分析栈Yy_d与Yy_pushtabvoid str_to_st1(string str,int st1); /对输入字符串的转换 void Foreparser(sqstack st,int Yy_pushtab134,int Yy_d2647, int st1,string str); /预测分析法int Yy_pushtab134,Yy_d2647; int st1stringsize;string str;sqstack st;st=-1; /分析栈的初始化 st+; st.datast=263; /分析栈初始化"#" cout<<"请输入字符串:"cin>>str;cout<<"栈(符号) "<<" 栈(数值)"<<" 输入串 "<<"What_to_do"<<endl; str_to_st1(str,st1); init(Yy_pushtab,Yy_d);Foreparser(st,Yy_pushtab,Yy_d,st1,str); return 0;void out(sqstack st,string str,int sp,int k)/输出函数 int n,m=0;for(int i=0;i<=sp;i+)/输出栈(符号)if(st.datai<7)cout<<word2st.datai<<" "n=word2st.datai.length()+1;else cout<<word1st.datai-256<<" "n=word1st.datai-256.length()+1; m=n+m; for(i=m;i<30;i+) cout<<" " for(i=0;i<=sp;i+) /输出栈(数字)cout<<setiosflags(ios:left)<<setw(3)<<st.datai<<" " for(int h=sp+1;h<6;h+)cout<<" " for(int j=k;j<strlen(str.c_str();j+) /输出输入串 cout<<strj; for(int g=strlen(str.c_str()-k;g<10;g+) cout<<" " cout<<" " void init(int Yy_pushtab134,int Yy_d2647) /初始化分析栈Yy_d与Yy_pushtabint i,j; ifstream infile1("1.txt",ios:in); ifstream infile2("2.txt",ios:in);for(i=0;i<13;i+)for(j=0;j<4;j+)infile1>>Yy_pushtabij;/cout<<Yy_pushtabij<<" " /cout<<endl; for(i=256;i<264;i+)for(j=0;j<7;j+)infile2>>Yy_dij;/cout<<Yy_dij<<" " / cout<<endl;in();in();void str_to_st1(string str,int st1) /对输入字符串的转化for(int i=0;i<strlen(str.c_str();i+)switch(stri)case'(': st1i=4; break;case'+': st1i=2; break;case')': st1i=5; break;case'': st1i=1; break;case'*': st1i=3; break;case'#': st1i=0; break;default :st1i=7; if(stri>='0'&&stri<='9') st1i=6;void Foreparser(sqstack st,int Yy_pushtab134,int Yy_d2647, int st1,string str) /预测分析法int i,k=0,what_to_do;while(st!=-1) out(st,str,st,k);if(st.datast>=0&&st.datast<=6)/栈顶元素为终结符if(st.datast!=st1k)cout<<"未能分析成功"<<endl; break;else st-;k+;cout<<endl;else /栈顶元素为非终结符what_to_do=Yy_dst.datastst1k; cout<<what_to_do<<endl; /输出what_to_doif(what_to_do=-1)cout<<str<<"不是本文法句子。"<<endl;break;else st-;for(i=0;i<4;i+) /把Yy_pushtabwhat_to_do中列出的全部常数压入分析栈 if(Yy_pushtabwhat_to_doi!=-1&&Yy_pushtabwhat_to_doi!=0) st+; st.datast=Yy_pushtabwhat_to_doi;if(st=-1&&st1k=0)cout<<str<<"是本文法句子。"<<endl; 文件1内容 257 1 258 0 256 0 -1 -1 0 -1 -1 -1 260 259 0-1 0 -1 -1 -1 260 259 2 0 0 -1 -1 -1 262 261 0 -1 262 261 2 0 0 -1 -1 -1 5 258 4 0 6 0 -1 -1 256 0 -1 -1 文件2内容 -1 0 -1 -1 0 -1 0 2 1 -1 -1 1 -1 1 -1 4 -1 -1 3 4 3 -1 -1 -1 -1 7 -1 7 -1 6 5 -1 -1 6 -1 -1 -1 -1 -1 10 -1 11 -1 9 9 8 -1 9 -1 -1 12 -1 -1 12 -1 12第 6 页