lex/yacc实现计算器

来源:互联网 发布:香港买mac转运到大陆 编辑:程序博客网 时间:2024/06/05 14:21

cal.y

%{#include <stdio.h>#include "lex.yy.c"#define YYSTYPE int  int yyparse(void);%}%token INTEGER PLUS MINUS TIMES DIVIDE LP RP%%command : exp {printf("%d/n",$1);}exp: exp PLUS term {$$ = $1 + $3;}    |exp MINUS term {$$ = $1 - $3;}    |term {$$ = $1;}    ;term : term TIMES factor {$$ = $1 * $3;}    |term DIVIDE factor {$$ = $1/$3;}    |factor {$$ = $1;}    ;factor : INTEGER {$$ = $1;}    | LP exp RP {$$ = $2;}    ;%%int main(){    return yyparse();}void yyerror(char* s){    fprintf(stderr,"%s",s);}int yywrap(){    return 1; }

cal.l

%{#include<string.h>  #include "y.tab.h"  extern int yylval;  %}  numbers ([0-9])+  plus "+"  minus "-"  times "*"  divide "/"  lp "("  rp ")"  delim [ /n/t]  ws {delim}*  %%  {numbers} {sscanf(yytext, "%d", &yylval); return INTEGER;}  {plus} {return PLUS;}  {minus} {return MINUS;}  {times} {return TIMES;}  {divide} {return DIVIDE;}  {lp} {return LP;}  {rp} {return RP;}  {ws}       ;   . {printf("Error");exit(1);}    %% 

使用方式:

yacc -d cal.y lex cal.lg++ -o cal y.tab.c 

运行./cal 然后输入3+4 ctrl+D就可以看到结果了

1 0
原创粉丝点击