码迷,mamicode.com
首页 > 其他好文 > 详细

词法分析器

时间:2016-10-16 19:43:36      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

//源代码
#include <stdio.h> #include <string.h> char string[80],simbol[8],ch; int wordID,index,m,n,sum; char *rwtab[6]={"begin","if","then","while","do","end"}; void scaner(void); main() { int index=0; printf("输入代码串(#号结束):"); do{ scanf("%c",&ch); string[index++]=ch; }while(ch!=#); index=0; do{ scaner(); switch(wordID) { case 11: printf("( %-10d%5d )\n",sum,wordID); break; case -1: printf("错误\n"); return 0; break; default: printf("( %-10s%5d )\n",simbol,wordID); break; } }while(wordID!=0); return 0; } void scaner(void) { sum=0; for(m=0;m<8;m++) simbol[m++]= NULL; ch=string[index++]; m=0; while((ch== )||(ch==\n)) ch=string[index++]; if(((ch<=z)&&(ch>=a))||((ch<=Z)&&(ch>=A))) { while(((ch<=z)&&(ch>=a))||((ch<=Z)&&(ch>=A))||((ch>=0)&&(ch<=9))) { simbol[m++]=ch; ch=string[index++]; } index--; wordID=10; for(n=0;n<6;n++) if(strcmp(simbol,rwtab[n])==0) { wordID=n+1; break; } } else if((ch>=0)&&(ch<=9)) { while((ch>=0)&&(ch<=9)) { sum=sum*10+ch-0; ch=string[index++]; } index--; wordID=11; } else { switch(ch) { case <: simbol[m++]=ch; ch=string[index++]; if(ch===) { wordID=22; simbol[m++]=ch; } else { wordID=20; index--; } break; case >: simbol[m++]=ch; ch=string[index++]; if(ch===) { wordID=24; simbol[m++]=ch; } else { wordID=23; index--; } break; case +: simbol[m++]=ch; ch=string[index++]; if(ch==+) { wordID=17; simbol[m++]=ch; } else { wordID=13; index--; } break; case -: simbol[m++]=ch; ch=string[index++]; if(ch==-) { wordID=29; simbol[m++]=ch; } else { wordID=14; index--; } break; case !: ch=string[index++]; if(ch===) { wordID=21; simbol[m++]=ch; } else { wordID=31; index--; } break; case =: simbol[m++]=ch; ch=string[index++]; if(ch===) { wordID=25; simbol[m++]=ch; } else { wordID=18; index--; } break; case *: wordID=15; simbol[m++]=ch; break; case /: wordID=16; simbol[m++]=ch; break; case (: wordID=27; simbol[m++]=ch; break; case ): wordID=28; simbol[m++]=ch; break; case {: wordID=5; simbol[m++]=ch; break; case }: wordID=6; simbol[m++]=ch; break; case ;: wordID=26; simbol[m++]=ch; break; case \": wordID=30; simbol[m++]=ch; break; case #: wordID=0; simbol[m++]=ch; break; case :: wordID=17; simbol[m++]=ch; break; default: wordID=-1; break; } } simbol[m++]=\0; }

运行截图

技术分享

 

词法分析器

标签:

原文地址:http://www.cnblogs.com/hano/p/5967323.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!