桂林电子科技大学编译原理课程设计说明书 第31页
extern string s_NT;
extern int feCount,tpCount; int actionLen;//action的长度
int parseInt(string);
string test(string Action[12][6],int Goto[12][3],string input) {
int top_st;//状态栈的栈顶变量 int subScript=0;//输入串的下标
//char tmp;//临时变量,用于对字符串到字符的转换
char ch=input[subScript];//取输入串数组中的当前字符
stack
while(1) { top_st=s_state.top();//取得状态栈的栈顶元素 int index = get_index(ch); string action=Action[top_st][index]; actionLen=action.length(); cout<<\action=\ if(action[0]=='S') { string rString= action.substr(1,actionLen-1); int tmp_int = parseInt(rString); s_sign.push(ch); //压入到符号栈的是当前字符,只是转换查action的时候要找类型 s_state.push(tmp_int); ch=input[++subScript];//提取下一个输入串的字符 } else if(action[0]=='r')//需要进行规约 { string rString= action.substr(1,actionLen-1); int tmp_int = parseInt(rString); int k=p[tmp_int].right.length();//取得该条文法的长度 //cout<<\ for(int i=0;i 桂林电子科技大学编译原理课程设计说明书 第32页 { s_state.pop(); char pop_sign = s_sign.top(); s_sign.pop(); char ttt[10]; string x=\ if( pop_sign>='a' && pop_sign<='z' ) { // cout<<\ \ result\ result.push(x+pop_sign); // cout<<\ result.top()= \ } else if(pop_sign == '+'||pop_sign == '*') { if(pop_sign == '+') fe[feCount].op = '+'; else fe[feCount].op = '*'; fe[feCount].x1 = result.top(); result.pop(); fe[feCount].x2 = result.top(); result.pop(); // fe[feCount].re = tpCount+\ fe[feCount].re += \ itoa(tpCount, ttt,10); fe[feCount].re += ttt; result.push(fe[feCount].re); feCount++; tpCount++; } } char A=p[tmp_int].left;//取得文法左部的字符 index = get_index(A); int j=Goto[s_state.top()][index];//规约 s_sign.push(A); s_state.push(j); } to 桂林电子科技大学编译原理课程设计说明书 第33页 else if(action==\ { //cout<<\表达式正确!\ break; } else { cout<<\表达式错误! \ cout<<\错误字符为\ break; } } for(int t=0;t return result.top(); } int main() { string Action[12][6]={ {\ {\ {\ {\ {\ {\ {\ {\ {\ {\ {\ {\ int Goto[12][3]={{1,2,3}, {-1,-1,-1}, {-1,-1,-1}, {-1,-1,-1}, {8,2,3}, {-1,-1,-1}, {-1,9,3}, {-1,-1,10}, {-1,-1,-1}, {-1,-1,-1}, 桂林电子科技大学编译原理课程设计说明书 第34页 {-1,-1,-1}, {-1,-1,-1}}; init();//初始化操作 //测试中缀转后缀 freopen(\ string input; cout< while(cin>>input) { s_state.push(0); s_sign.push('#'); cout<<\\ while(s_state.empty()==false)s_state.pop(); while(s_sign.empty()==false)s_sign.pop(); feCount = 0; tpCount = 0; } return 0; } int parseInt(string str) { int len = str.length(); int sum = 0; float carry = 1.0/10; for(int i=0; i carry *= 10; sum += (str[len-1-i]-'0')*carry; } return sum; }
相关推荐: