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
系统软件开发实践 贾志杰