flex&bison 第二版 实例 fb1-5

fb1-5.y

%{
   #include<stdio.h>	
%}

%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%token OP CP

%%

calclist:
 | calclist exp EOL {printf("= %d\n",$2);}
 ;

exp: factor {$$ = $1;}
 | exp ADD factor { $$ = $1 + $3;}
 | exp SUB factor { $$ = $1 - $3;}
 ;

factor: term {$$ = $1;}
 | factor MUL term { $$ = $1 * $3;}
 | factor DIV term { $$ = $1 / $3;}
;

term: NUMBER {$$ = $1;}
 | ABS term { $$ = $2 >= 0? $2:-$2;}
 | OP exp CP {$$ = $2;}
;

%%

int main(int argc,char **argv){
    yyparse();
}

fb1-5.l

%{
   #include "fb1-5.tab.h"
%}

%%
"+"     {return ADD;}
"-"     {return SUB;}
"*"     {return MUL;}
"/"     {return DIV;}
"|"     {return ABS;}
[0-9]+  {yylval = atoi(yytext); return NUMBER;}
"("     {return OP;}
")"     {return CP;}
\n      {return EOL;}
"//".*    {printf("正确答案%s\n",yytext);}
[ \t]   {}
.       {printf("%s\n",yytext);}
%%

命令终端执行下面的命令(先进入文件所在的路径)   ubuntu 14系统

bison -d fb1-5.y
flex fb1-5.l
gcc -o cal fb1-5.tab.c lex.yy.c -lfl -ly           注: cal是自己随便给要生成的可执行文件命的名,书上是cc,之前一直报错
./cal < testfile                                   注: testfile 中是测试样例

执行结果:

// testfile中内容

    1+2-3*4    //ans = -9
    2*5        //ans = 10
    1/2*3      //ans = 0
    (2-3)*(4/2)-5  //ans = -7

系统软件开发实践 贾志杰

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值