logo资料库

编译原理 词法分析 代码.docx

第1页 / 共3页
第2页 / 共3页
第3页 / 共3页
资料共3页,全文预览结束
#include #include char prog[80],token[8]; char ch; char num[10]=""; char iden[10]=""; int syn,p,m,n,sum,x,a,b; char * rwtab[8]={"VAR","BEGIN","ELSE","END","IF","THEN","REAL","INTEGER"}; main() { p=0; printf("\nplease input string:"); do { ch=getchar(); prog[p++]=ch; }while(ch!='\n'); p=0; do { scaner(); switch(syn) { case 3:num[a++]=sum;printf("%d",sum);printf("(%d,%d)\n",syn,sum);break; case 1:printf("%s",token);printf("(%d,%d)\n",syn,n);break; case -1:printf("input error\n"); break; case 4:strcat(iden,token);printf("%s",token);printf("(%d,%d)\n",syn,x);break; default:printf("%s",token);printf("(%d,%d)\n",syn,x); } }while(syn!=0); a=0,b=0; printf("CT:"); do {printf("%d,",num[a++]);}while(num[a]!=0); printf("\n"); printf("LT:"); printf("%s",iden); getch(); } /*词法扫描程序:*/ scaner() { for(n=0;n<8;n++)
token[n]=NULL; m=0; ch=prog[p++]; while(ch==' ')ch=prog[p++]; if((ch<='z'&&ch>='a')||(ch<='Z'&&ch>='A')) { while((ch<='z'&&ch>='a')||(ch<='Z'&&ch>='A')) { token[m++]=ch; ch=prog[p++]; } token[m++]='\0'; ch=prog[--p]; syn=4; for(n=0;n<8;n++) if(strcmp(token,rwtab[n])==0) { syn=1; break; } } else if((ch<='9'&&ch>='0')) { sum=0; while((ch<='9'&&ch>='0')) { sum=sum*10+ch-'0'; ch=prog[p++]; } ch=prog[--p]; syn=3; } else switch(ch) { case ':':token[m++]=ch; ch=prog[p++]; if(ch=='=') { token[m++]=ch; syn=2; x=1; }
else { syn=2; x=2; ch=prog[--p]; }break; case '+':syn=2;token[0]=ch;x=4;break; case '-':syn=2;token[0]=ch;x=3;break; case '*':syn=2;token[0]=ch;x=5;break; case '=':syn=2;token[0]=ch;x=0;break; case ';':syn=2;token[0]=ch;x=6;break; case '\n':syn=0;token[0]=ch;x=0;break; default:syn=-1; } }
分享到:
收藏