私人定制词法分析,能够在输入一整段句子时准确地进行词法分析,并提供种别码表。
通过定义数组循环不断读入与分析单词。
先判断单词是否为数字,如是标志符再进一步判断是关键字、界符还是标识符。
每次读完单词执行一次getchar()后重复循环,当输出##时退出循环。
图片、源代码如下:
#include<stdio.h> #include<string.h> #define Max 100 int JdujeNumber(char Words[],int i,int N); int JdujeKeywords(char Words[]); char *table[Max][1]={"#","begin","if","then","while","do","end","l(l|d)*","dd*","+","-","*","/",":",":=","<","<=","<>",">",">=","=",";","(",")"}; char Words[Max]; main() { int j,i=0,key; printf("\n各种单词符号对应的种别码\n"); for(j=0;j<23;j++) { printf("%s\t%d\t\t",table[j][0],j); if(j%2==0) printf("\n"); } printf("请输入:(输入##代表结束)"); do { scanf("%s",Words); if(strcmp(Words,"##")==0) break; j=JdugeNumber(Words,i,strlen(Words)); if(j==1) printf("%s\t是数字\n",Words); else if(j==0) { key=JdujeKeywords(Words); if(key>=0&&key<=7) { printf("%s\t是关键字\n",Words); } else if(key>7&&key<=22) { printf("%s\t是界符\n",Words); } else { printf("%s\t是标识符\n",Words); } } getchar(); }while(1); printf("程序结束!"); } int JdugeNumber(char Words[],int i,int N) { if(i==N) return 1; if(Words[i]>47&&Words[i]<58) { JdugeNumber(Words,i+1,N); } else return 0; } int JdujeKeywords(char Words[]) { int i; for(i=0;i<23;i++) { if(strcmp(Words,table[i][1])==0) return i; } return -1; }
时间: 2024-09-30 10:22:27