使用 Lex 和 Yacc 的计算器

Calculator using Lex and Yacc

是否可以用 lex 和 Yacc 构造一个简单的算术计算器?

如果是,请在继续之前获取concepts/methods我应该理解的内容。

Reference

注意 : 在 post 提问之前你应该搜索它,下面我要 post 的答案是从上面的 link 中获得的,我从一个google 搜索。

以下代码是使用YACC和LEX实现计算器程序

cal.l

DIGIT [0-9]+\.?|[0-9]*\.[0-9]+

%option noyywrap

%%

[ ]
{DIGIT} { yylval=atof(yytext); return NUM;}
\n|. {return yytext[0];}

cal.y

%{
#include<ctype.h>
#include<stdio.h>
#define YYSTYPE double
%}
%token NUM

%left ‘+’ ‘-‘
%left ‘*’ ‘/’
%right UMINUS

%%

S : S E ‘\n’ { printf(“Answer: %g \nEnter:\n”, ); }
| S ‘\n’
|
| error ‘\n’ { yyerror(“Error: Enter once more…\n” );yyerrok; }
;
E : E ‘+’ E { $$ =  + ; }
| E’-‘E { $$=-; }
| E’*’E { $$=*; }
| E’/’E { $$=/; }
| ‘(‘E’)’ { $$=; }
| ‘-‘E %prec UMINUS { $$= -; }
| NUM
;
%%

#include “lex.yy.c”

int main()
{
printf(“Enter the expression: “);
yyparse();
}

yyerror (char * s)
{
printf (“% s \n”, s);
exit (1);
}