www.pudn.com > yufa.rar > yufa.cpp


#include 
#include 
#include  
#include 
#include 
#include 
 
/*关键字*/ 
typedef struct keyword 
{ 
	char *name; 
    int code; 
}keyword; 
 
keyword key[11]={{"begin",1},{"end",2},{"if",3},{"then",4},{"else",5}, 
{"for",6},{"do",7},{"while",8},{"and",9},{"or",10},{"not",11}}; 
 
#define ID 12 
#define INT 13 
#define ADD 14 
#define MIN 15 
#define MUL 16 
#define DIV 17 
#define LT 18 
#define LE 19 
#define EQ 20 
#define GE 21 
#define GT 22 
#define NE 23 
#define EVA 24 
#define LP 25 
#define RP 26 
#define SEM 27 
 
/*相关初始化*/ 
FILE *in,*outfile;//输入输出文件指针 
char token[50];//存储一个单词词文中的各个字符 
int error_count=0;//错误计数 
int b;//记录数值大小 
int k;//记录标识符长度 
char ch1;//辅助变量 
int row=0;//代码行数 
int queue=0;//代码列数 
 
/*报错函数*/ 
void report_error(int a) 
{ 
	error_count++; 
	switch(a) 
	{ 
	case 1:cout<<"标识符长度超过6,不合法"<<"   "<<"行"<=0))//判断是否超过数值最大表示范围 
						out(token,INT);					 
					else  
					{ 
						if(b>65535) 
							report_error(3); 
					} 
				}                 
			} 
			else 
			{ 
				switch(ch) 
				{ 
				case'<': 
					ch=fgetc(in); 
					if(ch=='=') 
						out("<=",LE);					 
					else  
					{ 
						if(ch=='>') 
							out("<>",NE); 
						else  
						{ 
							fseek(in,-1,1); 
							out("<",LT); 
						} 
					} 
					break; 
				case'=': 
					out("=",EQ);					 
					break; 
				case'>': 
					ch=fgetc(in); 
					if(ch=='=') 
						out(">=",GE);					 
					else 
					{ 
						fseek(in,-1,1); 
						out(">",GT); 
					} 
					break; 
				case'+': 
					out("+",ADD); 
					break; 
				case'-': 
					out("-",MIN); 
					break; 
				case'*': 
					out("*",MUL); 
					break; 
				case'/': //对注释和除的区分 
					ch=fgetc(in); 
					if(ch=='*')  
					{ 
						while(1) 
						{  
							ch=fgetc(in); 
							if(ch==EOF) 
							{  
								report_error(4); 
								break; 
							} 
							if(ch=='*') 
							{  
								ch1=ch; 
								ch=fgetc(in); 
								if(ch=='/') 
								{  
									ch=fgetc(in); 
									break; 
								} 
							} 
						} 
					}					 
					else  
					{ 
						out("/",DIV); 
						break; 
					} 
				case':': 
					ch=fgetc(in); 
					if(ch=='=') 
						out(":=",EVA); 
					break; 
				case'(':out("(",LP); 
					break; 
				case')': 
					out(")",RP); 
					break; 
				case';': 
					out(";",SEM); 
					break; 
				case' ': 
					queue++;break; 
				case'\t': 
					break;	       
				case'\n': 
					row++; 
					break;					 
				default: 
					report_error(2); 
					break; 
				} 
			} 
		} 
	} 
} 
 
void main() 
{    
	char filename[30]; 
	cout<<"输入您要编译的文件名:"<>filename; 
	if((in=fopen(filename,"rt"))==NULL) 
	{ 
		printf("抱歉您要编译的文件 %s 有问题,请检查。\n",filename); 
		exit(1); 
	} 
	fopen("finish.txt","wr"); 
	scanner(); 
	cout<<"**********************************************"<