词法分析程序,但是老输不出分析的结果
程序代码:
[local]2[/local]#include <iostream.h> #include <stdlib.h> #include <stdio.h> #include <string.h> char prog[80], token[8]; char ch; int syn, p, m, n, sum=0; char * rwtab[6]={"begin","if","then","while","do","end"}; void scaner() { //分别是标示符、数字、符号,对应下面的 if else if 和 else for(n=0;n<8;n++) token[n]=NULL;//初始化 ch=prog[p++];//读下一个 字符 while(ch==' ') ch=prog[p++]; if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) //ch是字母字符,可能是关键字或者变量名 { m=0; while((ch>='0'&&ch<='9')||(ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))//ch为字母字符或数字字符 { token[m++]=ch; ch=prog[p++]; } token[m++]='\0'; p--; //回退一个字符 syn=10; for(n=0;n<6;n++) //将识别出来的字符和已定义的关键字作比较, if(strcmp(token,rwtab[n])==0) { syn=n+1; break; } } else if((ch>='0'&&ch<='9')) //ch是数字字符 { sum=0; while((ch>='0'&&ch<='9')) { sum=sum*10+ch-'0'; ch=prog[p++]; } p--;//回退一个字符 syn=11; if(sum>32767) syn=-1; } else switch(ch) //其他字符 { case'<':m=0;token[m++]=ch; ch=prog[p++]; if(ch=='>') { syn=21; token[m++]=ch; } else if(ch=='=') { syn=22; token[m++]=ch; } else { syn=23; p--; } break; case'>':m=0;token[m++]=ch; ch=prog[p++]; if(ch=='=') { syn=24; token[m++]=ch; } else { syn=20; p--; } break; case':':m=0;token[m++]=ch; ch=prog[p++]; if(ch=='=') { syn=18; token[m++]=ch; } else { syn=17; p--; } break; case'*':syn=13;token[0]=ch;break; case'/':syn=14;token[0]=ch;break; case'+':syn=15;token[0]=ch;break; case'-':syn=16;token[0]=ch;break; case'=':syn=25;token[0]=ch;break; case';':syn=26;token[0]=ch;break; case'(':syn=27;token[0]=ch;break; case')':syn=28;token[0]=ch;break; case'#':syn=0;token[0]=ch;break; case'\n':syn=-2;break; default: syn=-1;break; } } void main() { FILE *fin=fopen("in.txt","r"); FILE *fout=fopen("out.txt","w"); p=0; printf("程序如下:\n"); while(!feof(fin)&&ch!='#') { ch=fgetwc(fin); prog[p]=ch; printf("%c",prog[p]); p++; } printf("\n********************词法分析如下*********************\n"); p=0; do{ scaner(); switch(syn) { case 11: printf("%d","%d",syn,sum); break; case -1: printf("error"); break; default: printf("%c","%d",syn,token); } } while (syn!=0); fclose(fin); fclose(fout); }
in.rar
(456 Bytes)