用c语言对一个简单的语言的子集编制一个一遍扫描的编译程序
#include <iostream> #include <string.h> #include <ctype.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 scanner() { m=0; for(n=0;n<8;n++) token[n]=NULL; ch=prog[p++]; while(ch==‘ ‘)ch=prog[p++]; if(isalpha(ch))//字母字符 { while(isdigit(ch)||isalpha(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(isdigit(ch))//数字字符 { sum=0; while(isdigit(ch))//shuzi { sum=sum*10+ch-‘0‘; ch=prog[p++]; } p--; syn=11; } else switch(ch) { case ‘<‘: m=0; token[m++]=ch; ch=prog[p++]; if(ch==‘>‘) { syn=22; token[m++]=ch; } else if(ch==‘=‘) { syn=22; token[m++]=ch; } else { syn=20; p--; } break; case ‘>‘:token[m++]=ch; ch=prog[p++]; if(ch==‘=‘) { syn=24; token[m++]=ch; } else { syn=23; p--; } break; case ‘:‘: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; default:syn=-1; } } void main() { using namespace std; p=0; int i; printf("\n please input string:\n"); do{ ch=getchar(); prog[p++]=ch; }while(ch!=‘#‘); p=0; do{ scanner(); switch(syn) { case 11:printf("(%d,%d)",syn,sum); break; case -1:printf("ERROR!"); break; default: printf("(%d,",syn); for(i=0;i<strlen(token);i++) { printf("%c",token[i]); } printf(")"); } }while(syn!=0); } |