用lex和yacc写个计算器

直接贴代码了

%{
#include <stdio.h>
#include <string.h>
#include "y.tab.h"

int yywrap(void)
{
	return 1;
}
%}
%%
"+"	return ADD;
"-"	return SUB;
"*"	return MUL;
"/"	return DIV;
"\n"	return CHANGELINE;
"("	return LEFT;
")"	return RIGHT;
"="	return EQ;
([1-9][0-9]*)|0|([0-9]+\.[0-9]*) {
	double temp;
	sscanf (yytext, "%lf", &temp);
	yylval.var = temp;
	return NUMBER;
}
([a-zA-Z]+) {
	yylval.name = strdup(yytext);
	return NAME;
}
[ \t] ;
%%
%{
#include <stdio.h>
#include <string.h>
int yylex();
int yyerror(char*);
int count = 0;
char* str[100];
double value[100];
%}
%union
{
	double var;
	char* name;
}
%token <var> NUMBER
%token <name> NAME
%token ADD SUB MUL DIV CHANGELINE LEFT RIGHT EQ
%type <var> term exp factor
%%
lines:
     	line
	|lines line;
line:
    	CHANGELINE
	|exp CHANGELINE
	{
		printf(">>  %f\n", $1);
	}
      	|NAME EQ exp CHANGELINE
	{
		int i = 0;
		int flag = 1;
		for (i = 0; i < count; ++i)
			if (strcmp($1, str[i]) == 0)
			{
				value[i] = $3;
				flag = 0;
				break;
			}
		if (flag)
		{
			str[count] =(char*) $1;
			value[count] = $3;
			count++;
			printf("new variable added\n");
		}
	}

exp:
	term
    	|exp ADD term
	{
		$$ = $1 + $3;
	}
	|exp SUB term
	{
		$$ = $1 - $3;
	}
term:
   	factor
	|term MUL factor
	{
		$$ = $1 * $3;
	}
	|term DIV factor
	{
		$$ = $1 / $3;
	}
factor:
      	NUMBER
	|LEFT exp RIGHT 
	{
		$$ = $2;
	}
	|NAME
	{
		int i = 0;
		int flag = 1;
		for (i = 0; i < count; ++i)
		{
			if (strcmp($1, str[i]) == 0)
			{
				$$ = value[i];
				flag = 0;
				break;
			}
 
		}
		if(flag)
			printf("no this variable\n");
		
	}
%%
int main()
{	
	printf("support use variable\ninput ctrl+d to exit\n");
	extern int yyparse(void);
	yyparse();
	return 0;
}
int yyerror(char* msg)
{
	printf("error:%s\n", msg);
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值