c语言实现算符优先语法分析

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

#includestdio.hcharprog[100],zhongjian[100],shu[500];charch,zh;intsyn,p,q,a,b,c,d;//p指向prog,q指向zhongjianinttable[8][8]={{1,1,-1,-1,-1,1,-1,1},{1,1,-1,-1,-1,1,-1,1},{1,1,1,1,-1,1,-1,1},{1,1,1,1,-1,1,-1,1},{-1,-1,-1,-1,-1,-1,-1,0},{1,1,1,1,0,1,0,1},{1,1,1,1,0,1,0,1},{-1,-1,-1,-1,-1,0,-1,-1}};//存储算符优先关系表,大于为1,小于或等于为-1,其它为0表示出错charzhan[100];//数组栈intz,j;//z为栈顶指针,j为zhongjian数组指针voidpush(charch)//入栈{zhan[z++]=ch;}voidpop()//出栈{z--;}voidputzhan()//打印栈内字符{for(inti=0;iz;i++){printf(%c,zhan[i]);}printf(\t);}intputzhong()//打印数组中剩余字符{inti=j;do{printf(%c,zhongjian[i]);}while(zhongjian[i++]!='#');printf(\t);i-=2;returni;}charding()//获取栈顶元素,无视E{chara;q=z-1;do{a=zhan[q--];}while(a=='E');returna;}charding2()//获取栈顶元素{chara;q=z-1;a=zhan[q];returna;}intfindint(charch)/*将字符转为数字,以得到算符优先值*/{intt;switch(ch){case'+':t=0;break;case'-':t=1;break;case'*':t=2;break;case'/':t=3;break;case'(':t=4;break;case')':t=5;break;case'i':t=6;break;case'#':t=7;}returnt;}voidchu()//初始化{zhan[0]='#';z=1;c=0;j=0;syn=0;zh=ding();ch=zhongjian[j];}voidanalyse()//分析{while(zh!='#'||ch!='#'){putzhan();d=putzhong();a=findint(zh);b=findint(ch);if(table[a][b]==-1){push(ch);j++;printf(移进\n);}elseif(table[a][b]==1){for(intm=d;m=j;m--){shu[c++]=zhongjian[m];}for(inti=z-1;i0;i--){shu[c++]=zhan[i];}zh=ding2();if(zh=='i')//当前比较为i,出栈一次pop();else//当前比较不为i,出栈三次{pop();pop();pop();}push('E');//归约到Eprintf(归约\n);shu[c++]='';shu[c++]='';shu[c++]='-';shu[c++]='';}else{syn=-1;break;}zh=ding();ch=zhongjian[j];}}voidloadch()//读入所有字符串{inti=0;printf(请输入要进行算符优先分析的字符串:\n);do{ch=getchar();prog[i++]=ch;}while(ch!='#');}voidscaner(){syn=1;ch=prog[p++];while(ch==''||ch=='\n'){ch=prog[p++];}switch(ch){case'+':zhongjian[q++]='+';break;case'-':zhongjian[q++]='-';break;case'*':zhongjian[q++]='*';break;case'/':zhongjian[q++]='/';break;case'(':zhongjian[q++]='(';break;case')':zhongjian[q++]=')';break;case'i':zhongjian[q++]='i';break;case'#':zhongjian[q++]='#';syn=0;break;default:syn=-1;break;}}voidsaomiao(){p=0;q=0;do{scaner();if(syn==-1){printf(输入符号有误!\n);break;}}while(syn!=0);}voidmain(){loadch();saomiao();if(syn==0){chu();analyse();printf(#E\t#\t结束\n);if(syn==0){printf(该字符串可被文法识别\n);printf(E);for(inti=c;i=0;i--){printf(%c,shu[i]);}printf(\n);}else{printf(该字符串不可被文法识别\n);}}}

1 / 5
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功