⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 by2.cpp

📁 一个递归算法的算法
💻 CPP
字号:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdarg.h>
#include<stdlib.h>

#define EOI 0
#define BEGIN 1
#define END 2
#define IF 3
#define THEN 4
#define ELSE 5
#define FOR 6
#define DO 7
#define WHILE 8
#define AND 9
#define OR 10
#define NOT 11
#define ID 12
#define INT 13
#define PLUS 14		//+
#define MINUS 15	//-
#define MULT  16    //*
#define FEN   17    //;
#define LP 18		//(
#define RP 19       //)
#define LT 20		//<
#define LE 21		//<=
#define EQ 22		//=
#define NE 23		//<>
#define GT 24		//>
#define	GE 25		//>=
#define MH 26		//:
#define FZ 27		//:=
#define XIE 28		///
#define ZHX 29		///

void expression(void);

FILE *fp;
char ch;
int bianma;		//advance()提取的类型编码
int error_flag=0;
int count=0;


int match(int bm){
//int result;
if(bm==bianma)
return 1;
else return 0;
}


void advance(){
char t[10];
int i=0;
//char *pt;

//pt=t;
ch=fgetc(fp);
while((ch!='(')&&(ch!=EOF))
	ch=fgetc(fp);
ch=fgetc(fp);
while((ch!=',')&&(ch!=EOF))
{
	t[i]=ch;
	i++;
	ch=fgetc(fp);
}
t[i]='\0';
count++;
bianma=atoi(t);

}//取二元式中的数字,最后一次ch中为,



int legal_lookahead(int first,...){
va_list args;	//可变长
int tok;
int lookaheads[16];
int *p=lookaheads;
int *cur;
//int error_print=0;
int rval=0;

va_start(args,first);	//args指向first的下一个

if(!first)
{
	if(match(EOI))
		rval=1;
}
else
{
	*p=first;
	while((tok=va_arg(args,int))&&p<&lookaheads[16])	//当前的args赋给tok,args向后指一个
		*++p=tok;
	while(!match(FEN))
	{
		for(cur=lookaheads;cur<=p;cur++)
		{	if(match(*cur))
			{
				rval=1;
				goto exit;
		}}
		
			printf("%d error\n",count);
			//error_print=1;
			error_flag=1;
		
		advance();
	}
}

exit:
	va_end(args);

	return rval;
}



void factor(){
	if(!legal_lookahead(ID,LP,0))//12,18
		return;
	if(match(ID))
		advance();
	else if(match(LP))
	{
		advance();
		expression();
		if(match(RP))	//19
			advance();
		else
		{printf("Insert missing rp after %d \n",count-1);
		 error_flag=1;
		}
	}
	else
	{	printf("error3\n");
		error_flag=1;
	}
}



void term(){
	if(!legal_lookahead(ID,LP,0))
		return;
	factor();
	while(match(MULT)||match(XIE))//16,28
	{
		advance();
		factor();
	}
}



void expression(){
	
	term();
	while(!match(EOI))
	{
		if(match(PLUS)||match(MINUS))	//14,15
		{
		advance();
		term();
		return;
		}
		else{
			printf("Insert missing plus or minus after %d \n",count-1);
			error_flag=1;
			term();
		
		}
	}
}




void main(){
char fir[5];
int j=0;

fp=fopen("test.txt","r");
if(fp==NULL)
  printf("cannot open file\n");
else 
{	ch=fgetc(fp);

    /*while((ch!='(')&&(ch!=EOF))
	ch=fgetc(fp);*/

    ch=fgetc(fp);
    while(ch!=',')
	{
	fir[j]=ch;
	j++;
	ch=fgetc(fp);
	}
	fir[j]='\0';
	count++;
	bianma=atoi(fir);
	//printf("%d\n",bianma);

expression();
	
}

if(error_flag==0)
printf("success!\n");

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -