2016-10-16 16 views
0

私はbisonとflexを使って電卓の例をテストしています。サンプルコードは、ファイル "RPN-すべてcalc2.y" で、次のとおりです。bison + flexを使って電卓を書くには

%{ 
#define YYSTYPE double 
#include <math.h> 
#include <stdio.h> 
#include <stdlib.h> 
int yyerror(const char* s); 
int yylex(void); 
%} 
%token NUM 
%% /* grammer rules and actions follow */ 
input: /* empty */ 
    | input line 
    ; 
line: '\n' 
    | exp '\n' { printf("\t%.10g\n", $1); } 
    ; 
exp: NUM { $$ = $1; } 
    | exp exp '+' { $$ = $1 + $2; } 
    | exp exp '-' { $$ = $1 - $2; } 
    | exp exp '*' { $$ = $1 * $2; } 
    | exp exp '/' { $$ = $1/$2; } 
    | exp exp '^' { $$ = pow($1, $2); } 
    | exp 'n' { $$ = -$1; } 
    ; 
%% 
#include <ctype.h> 
int yylex(void) 
{ 
int c; 
while ((c = getchar()) == ' '||c == '\t') ; /* skip white spaces*/ 
if (c == '.' || isdigit(c)) /* process numbers */ 
{ 
ungetc(c, stdin); 
scanf("%lf", &yylval); 
printf("value is %lf\n",yylval); 
return NUM; 
} 
if (c == EOF) return 0; 
printf("symbol is %c, %d",c,c); 
return c; } 
int yyerror(const char* s) { printf("%s\n", s); return 0; } 
int main(void) { return yyparse(); } 

それはうまく動作します。 私は次のようにこの計算を実装するためにフレックス+バイソンを使用したい: ファイル "rp.lex":

%option noyywrap 

%{ 
#include "rpn-all-calc3.tab.h" 
%} 

op [+\-*/^n]+ 
ws [ \t]+ 
letter [a-zA-Z] 
digit [0-9]+ 

%% 
{letter} REJECT; 
{digit} return NUM; 
{op}|\n return *yytext; 
{ws} /* eat up white spaces */ 

%% 

ファイル "RPN-すべて-calc2.y" は次のとおりです。

%{ 
#define YYSTYPE double 
#include <math.h> 
#include <stdio.h> 
#include <stdlib.h> 
int yyerror(const char* s); 
int yylex(void); 
%} 
%token NUM 
%% /* grammer rules and actions follow */ 
input: /* empty */ 
    | input line 
    ; 
line: '\n' 
    | exp '\n' { printf("\t%.10g\n", $1); } 
    ; 
exp: NUM { $$ = $1; } 
    | exp exp '+' { $$ = $1 + $2; } 
    | exp exp '-' { $$ = $1 - $2; } 
    | exp exp '*' { $$ = $1 * $2; } 
    | exp exp '/' { $$ = $1/$2; } 
    | exp exp '^' { $$ = pow($1, $2); } 
    | exp 'n' { $$ = -$1; } 
    ; 
%% 
#include <ctype.h> 
int main(void) { return yyparse(); } 
int yyerror(const char* s) { printf("%s\n", s); return 0; } 

あり、コンパイルではエラーではありません:

bison -d rpn-all-calc2.y 
flex -o rpn-all-calc3.lex.yy.c rp.lex 
gcc *.c -o test -lm 

は、しかし、私は "./test" を実行したときに、私が入力し、言う: 1 1 + その後、私は0を得ましたどのような式を入力しても、常に0になります。 私のコードで何が問題になっていますか? 私を助けてくれてありがとう!

答えて

1

フレックスレクサーでは、見つかった番号にyylvalを設定するのを忘れました。

あなたはああ

{digit} { sscanf(yytext, "%lf", &yylval); return NUM; } 
+0

にライン

{digit} return NUM; 

を変更することができます!できます!!ありがとうございました!!! – pfc