In larger program I have given the following (flex/bison)
In flex:
pn [\+|\-]
dig [0-9]+
exp [e|E]{dig}+
.
.
.
"+" {printf("+ detected\n");
return PLUS_SIGN;}
{pn}?{dig}+ { printf("digit detected - %s\n",yytext);
sscanf(yytext, "%d", (int*)&yylval);
return TYPE_INT;}
In Bison:
expr:
expr PLUS_SIGN expr
{
$$ = $1 + $3;
printf(" $$=%f\n",$$);
}
| TYPE_INT
{
$$ = (int)$1;
printf(" $$=%f\n",$$);
}
;
The problem is:
When I give 2+2 it recognizes 2 and +2 instead of 2 , + , 2
How can I get it to do the addition?
Don’t make the plus or minus sign (
{pn?}) part of the number token. Treat them as two separate tokens,+and2. Then flex won’t have any ambiguity to resolve.Instead, have bison handle the unary plus and minus operators. Make it the parser’s job, not the lexer’s.