Flex和Bison Calculator计算问题

时间:2014-03-05 19:21:47

标签: c compiler-construction bison flex-lexer

我试图让它从文件中读取值(例如1 + 2)并在控制台中输出答案。运算符工作正常并产生正确的结果,但输出中的初始值完全错误。例如,当我尝试5 + 3时,它显示为6432824 + 6432824 = 12865648,当再次运行时完全相同时,将其显示为4597832 + 4597832 = 9195664.所以即使5和3不同(显然)它们也会显示作为相同的数字,并且每次运行时看似随机。我该如何解决这个问题?

以下是代码:

Flex文件:

%{
    #include <stdio.h>
    #include <stdlib.h>
    #include "y.tab.h"
    extern  FILE* yyin;
            FILE* FileOutput;
    #define YYSTYPE int
%}

%%

[0-9]+  { yylval = (int)yytext; return INTEGER; }
"+" return ADD;
"-" return SUBTRACT;
"*" return MULTIPLY;
"/" return DIVIDE;
[ \t]  ;
.       yyerror();

%%

int main(int argc, char *argv[])
{
    yyin = fopen(argv[1], "r");
    FileOutput = fopen("output.c", "w");
    yyparse();
    fclose(FileOutput);
    return 0;
}

int yywrap(void)
{
 return 1;
}

int yyerror(void)
{
 printf("Error\n");
}

野牛档案:

%{
 #include <stdio.h>
 #include <stdlib.h>
 extern FILE* FileOutput;
 #define YYSTYPE int

 void createcode(int result, int a, unsigned char op, int b);

%}

%token INTEGER
%token ADD SUBTRACT MULTIPLY DIVIDE

%left ADD SUBTRACT
%left MULTIPLY DIVIDE


%%
program: 
        | program statement
        ;

statement:
        expression '\n'     { printf("%d\n", $1); }
        | error '\n'            { yyerrok; }
        ;

expression: 
        INTEGER         { $$ = $1; }
        | expression ADD expression     { $$ = $1 + $3, createcode($$, $1, '+', $3);}
        | expression SUBTRACT expression        { $$ = $1 - $3; createcode($$, $1, '-', $3);}
        | expression MULTIPLY expression        { $$ = $1 * $3; createcode($$, $1, '*', $3);}
        | expression DIVIDE expression      { $$ = $1 / $3; createcode($$, $1, '/', $3);}
        | '(' expression ')'            { $$ = $2; }
        ;

%%

void createcode(int result, int a, unsigned char op, int b)
{
    printf("%d %c %d = %d", a, op, b, result);
    fprintf(FileOutput, "%d %c %d = %d", a, op, b, result);
}

1 个答案:

答案 0 :(得分:0)

您将返回一个字符串(char *)而不是整数。最简单的解决方案是在yylex中使用strtol:

即,而不是:

[0-9]+  { yylval = (int)yytext; return INTEGER; }

尝试

[0-9]+  { yylval = (int)strtol(yytext, NULL, 10); return INTEGER; }