编译原理语法分析程序(最左推导)

文法G2的最左推导和最右推导

G2

E->E+T | E-T | T

T->T*F | T/F | F

F->(E) | n

G2的终结符集合VT

+,-,*,/,(,),

G2的非终结符集合VN

E,T,F,n

句子3+2*4最左推导

E

 

 

 

 

 

E

+

T

 

 

 

F

+

T

 

 

 

N

+

T

 

 

 

N

+

T

*

F

 

N

+

F

*

F

 

N

+

N

*

F

 

N

+

N

*

N

 

 

句子3+2*4最右推导:

E

 

 

 

 

 

E

+

T

 

 

 

E

+

T

*

F

 

E

+

T

*

N

 

E

+

F

*

N

 

E

+

N

*

N

 

F

+

N

*

N

 

N

+

N

*

N

 

 

 

语法树:

 代码实现:

 本人笔记的课程作业程序,不要抄袭
1
#include <iostream> 2 #include<string> 3 4 using namespace std; 5 string expr; 6 int step; 7 void analyze(int left,int right,char start); 8 9 int main() 10 { 11 cout << "please input a correct expression\n"; 12 getline(cin,expr); 13 analyze(0,expr.size(),'E'); 14 return 0; 15 } 16 void analyze(int left,int right,char start) 17 { 18 switch(start){ 19 case 'E':{ 20 int bracnt = 0; 21 bool binope = false; // flag of + or - 22 for(int i=right-1;i>=left;--i){ 23 if(expr[i] == '(')bracnt++; 24 if(expr[i] == ')')bracnt--; 25 if(!bracnt){ 26 if(expr[i]=='+' || expr[i]=='-'){ 27 binope = true; 28 cout << "step " << step << " : "; 29 cout << start << "->" << start << expr[i] << 'T' << endl; 30 step++; 31 analyze(left,i,'E'); 32 analyze(i+1,right,'T'); 33 break; 34 } 35 } 36 } 37 if(!binope){ 38 cout << "step " << step << " : "; 39 cout << start << "->" << 'T' << endl; 40 step++; 41 analyze(left,right,'T'); 42 } 43 break; 44 } 45 case 'T':{ 46 int bracnt = 0; 47 bool binope = false; // flag of * or / 48 for(int i=right-1;i>=left;--i){ 49 if(expr[i] == '(')bracnt++; 50 if(expr[i] == ')')bracnt--; 51 if(!bracnt){ 52 if(expr[i]=='*' || expr[i]=='/'){ 53 binope = true; 54 cout << "step " << step << " : "; 55 cout << start << "->" << start << expr[i] << 'F' << endl; 56 step++; 57 analyze(left,i,'T'); 58 analyze(i+1,right,'F'); 59 break; 60 } 61 } 62 } 63 if(!binope){ 64 cout << "step " << step << " : "; 65 cout << start << "->" << 'F' << endl; 66 step++; 67 analyze(left,right,'F'); 68 } 69 break; 70 } 71 case 'F':{ 72 if(expr[left] == '('){ 73 cout << "step " << step << " : "; 74 cout << start << "->" << "(E)" << endl; 75 step++; 76 analyze(left+1,right,'E'); 77 } 78 else{ 79 cout << "step " << step << " : "; 80 cout << start << "->" << "n" << endl; 81 step++; 82 } 83 break; 84 } 85 default:break; 86 } 87 }

 

posted on 2018-03-20 22:34  CreatorKou  阅读(3468)  评论(0编辑  收藏  举报

导航