【发布时间】:2014-03-05 19:21:47
【问题描述】:
我试图让它从文件中读取值(例如 1+2)并在控制台中输出答案。运算符工作正常并产生正确的结果,但输出中的初始值完全错误。例如,当我尝试 5+3 时,它显示为 6432824 + 6432824 = 12865648,当再次运行完全相同时,显示为 4597832 + 4597832 = 9195664。所以即使 5 和 3 不同(显然)它们也会显示作为相同的数字,并且每次运行时似乎都是随机的。我该如何解决这个问题?
代码如下:
弹性文件:
%{
#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);
}
【问题讨论】:
标签: c compiler-construction bison flex-lexer