It's based on this article but uses lex
instead of implement it myself.
But I've tried various expressions like 2+3
,all failed...
lex:
0 {
yylval = atoi(yytext);
}
[1-9][0-9]* {
yylval = atoi(yytext);
return NUM;
}
[-+*/()] {
return *yytext;
}
[ \t\n]+ ;
. yyerror("Unknown character");
yacc:
%start prob
%token NUM
%%
prob开发者_StackOverflow社区 : expr '\n'
{
printf("\t=%X\n", $1);
return 0;
}
;
expr : expr '+' term
{
$$ = $1 + $3;
}
| expr '-' term
{
$$ = $1 - $3;
}
| term
{
$$ = $1;
}
;
term : term '*' NUM
{
$$ = $1 * $3;
}
| term '/' NUM
{
$$ = $1/$3;
}
| '(' expr ')'
{
$$ = $2;
}
| NUM
{
$$ = $1;
}
;
%%
It's because of :
[ \t\n]+ ;
Move \n
to [-+*/()]
.
first upon remove test for 0 i.e.
0 {
yylval = atoi(yytext);
}
this wont help you.this should work now.
精彩评论