Lex & yacc Programming in linux.
Hi,
I developed an application using lex & yacc. It is a simple calculator which does add, subtract and multiplication. The program is compiled correctly without errors. But when i execute the program, it is giving 0 as output irrespective of input and the result is always 0.000. For example if the input is 3.2 + 4.5, the output is 0.000. I dont know where i have gone wrong. The programs are given below. cal.l ------ %{ #include "global.h" #include "y.tab.h" #include <stdlib.h> %} white [ \t]+ digit [0-9] integer {digit}+ real {integer}("."{integer})? %% {white} { } {real} {yyval=atof(yytext); return (NUMBER);} "+" return (PLUS); "-" return (MINUS); "*" return (TIMES); "\n" return (END); ------------------------------------------------- cal.y ------ %{ #include "global.h" #include <stdio.h> #include <stdlib.h> %} %token NUMBER %token PLUS MINUS TIMES %token END %left PLUS MINUS TIMES %start Input %% Input: | Input Line ; Line: END | Expression END {printf("\n Result: %f",$1);} ; Expression: NUMBER { $$=$1; } | Expression PLUS Expression { $$=$1+$3;} | Expression MINUS Expression { $$=$1-$3; } | Expression TIMES Expression { $$=$1*$3; } ; %% int yyerror(char *s) { printf("%s\n",s); } int main(void) { yyparse(); } global.h --------- #define YYSTYPE double extern YYSTYPE yyval; Result: ------- [root@mycal]# yacc -d cal.y [root@mycal]# lex cal.l [root@mycal]# gcc -o cal y.tab.c lex.yy.c -lfl [root@mycal]# ./cal 2.3+4.2 Result: 0.000000 [root@mycal]# Let know what is the problem and how to solve it. Thanx. |
I would recommend printing out all the arguments to make sure you are parsing them as you intended it too. It has been a long time since I have used lex and yacc but I am guessing you are getting 0's for all your values with that code.
This should probably be moved to the programming forum.... |
Ok... so I decided to do some debugging for you because I was bored...
You are setting yyval correctly. You are also correctly determining which operation you are doing. However, $1 is always 0.0000 when your number case comes up so this is where your problem lies. I'll leave the rest to you. |
All times are GMT -5. The time now is 10:06 PM. |