编译原理算符优先分析c++源代码.docxVIP

  • 28
  • 0
  • 约3.76千字
  • 约 6页
  • 2021-03-21 发布于天津
  • 举报
算符优先分析器源代码: #includeiostream #includeiomanip #define MAX 100 using namespace std; struct Stack // 符号栈 { char data[MAX]; int top; }; char Terminal[6]={;,(,),a,+,#}; // 终结符集合 char Table[6][6]={ // 算符优先关系表 {, , , , , }, I J J J J J J J {, , =, , , !}, {, , , !, , }, {, , , !, , }, {, , , , , !}, {, , !, , !, =} }; //判断是否为终结符,是返回其所在位置 i,否则返回-1 int Is_Vt(char ch,char Terminal[6]) { int i; for(i=0;i6;i++) { if(ch==Terminal[i]) // 输入符为终结符 return i; } return -1; } // 读入输入串,返回其长度 int Getchar(int length,char String[MAX]) { int i; cout***** 输入字符串的长度 length=; cinlength; coutendl***** 该输入串为: ; for(i=0;ilength;i++) cinString[i]; return length; } void PrintStack(Stack st, int top) // 输出栈中的内容 { for(int i=0;i=top;i++) coutst.data[i] ; cout \t\t; } int main() { Stack st; int length=0,Len,k; char String[MAX],ch; Len=Getchar(length,String); // 获得输入串 int j=0; ch=String[j]; // 指向第一个输入符 st.top=0;st.data[st.top]=#; // 将‘ #入栈 coutendl************************** endl;************************** endl; cout 符 号 栈 setw(15) 当 前 符 号 setw(15) 剩 余 输 入 串 setw(20) 移进或归约 endl; // 输出格式 while(st.top!=1 || ch!=#) { if(Is_Vt(ch,Terminal)!=-1) // 输入符为终结符 { k=Is_Vt(ch,Terminal); // 获取分析表 Table 的第二个下标 int m,t; //t 指向终结符在栈中的位置 if(Is_Vt(st.data[st.top],Terminal)!=-1) // 栈顶为终结符 { m=Is_Vt(st.data[st.top],Terminal);// 获取分析表 Table 的第 一个下标 t=st.top; } else // 栈顶为非终结符,看 top-1 { m=Is_Vt(st.data[st.top-1],Terminal);// 获取分析表 Table 的 第一个下标 t=st.top-1; } if(Table[m][k]== || Table[m][k]===) // 栈顶符号的优先级小 于等于输入符号,压栈 { PrintStack(st,st.top); // 输出栈中内容 coutchsetw(10); // 输出当前符号 for(int p=j+1;p=Len;p++) // 输出剩余输入串 coutString[p]; cout\t\t\t 移进 endl; // 输出下一步进行的操作 st.top++; st.data[st.top]=ch; // 输入符移进栈中 j++; ch=String[j]; // 指向下一输入符 } else if(Table[m][k]==!) // 两终结符的优先关系不确定 { coutendl*** 分析出错 !***endl; return 0; } else // 栈顶符号的优先级大于输入符,归约 { int q; // 表示分析表 Table 的行 if(Is_Vt(st.data[t-1],Terminal)!=-1) // 终结符相邻符号也是 终结符 { q=Is_Vt(st.data[t-1],Terminal);// 获得分析表 Table 的 行 t=t-1; // 获得分析表 Table 的列 } else //t-1 位置是一个非终结符 { q=Is_Vt

文档评论(0)

1亿VIP精品文档

相关文档