I tested this example of teamwork Flex and Bison, but the result of the calculation is not displayed in the console. test.l:
%{
#include "parser.tab.h"
%}
%option yylineno
%option noyywrap
%%
[/][/].*\n ; // comment
[0-9]+ { yylval = atoi(yytext);
return NUM;
}
[ \t\r\n] ; // whitespace
. { return *yytext; }
%%
parser.y:
%{
#include <stdio.h>
void yyerror(char *s) {
fprintf (stderr, "%s\n", s);
}
%}
%token NUM
%start EVALUATE
%%
EVALUATE: EXPR {printf("=%d\n", $$);} ;
EXPR: EXPR '+' TERM { $$ = $1 + $3; }
| EXPR '-' TERM { $$ = $1 - $3; }
| TERM
;
TERM: TERM '*' NUM { $$ = $1 * $3; }
| TERM '/' NUM { $$ = $1 / $3; }
| NUM
;
%%
int main()
{
return yyparse();
}
But if you add getchar(), then after you enter this additional character all the same calculation result is displayed. Why is not this change(EVALUATE: EXPR{printf("=%d\n", $$); getchar();} ;
) , I do not see the result?
Sorry for the my English.
You are parsing the input coming from
stdin
, which is a "stream". Before that stream is terminated, the parser cannot know the complete parse tree. For example, if you enter the expression1+1
, the complete input could as well be1+11
,1+1-1
or1+11*4
- different expressions that would lead to completely different parse trees as result.You can create a properly terminated input by doing one of the following:
echo "1+1" | ./parser
inputfile.txt
containing the input1+1
:./parser < inputfile.txt