Desk Calculator
// Lex file: desk.l
DIGIT [0-9]+\.?|[0-9]*\.[0-9]+
%%
[ ]
{DIGIT} {yylval=atof(yytext);return NUM;}
\n|. {return yytext[0];}
// Yacc file: desk.y
%{
#include<ctype.h>
#include<stdio.h>
#define YYSTYPE double
%}
%token NUM
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
S : S E '\n' { printf("Answer: %g \nEnter:\n", $2); }
| S '\n'
|
| error '\n' { yyerror("Error: Enter once more...\n" );yyerrok; }
;
E : E '+' E { $$ = $1 + $3; }
| E'-'E { $$=$1-$3; }
| E'*'E { $$=$1*$3; }
| E'/'E { $$=$1/$3; }
| '('E')' { $$=$2; }
| '-'E %prec UMINUS { $$= -$2; }
| NUM
;
%%
#include "lex.yy.c"
int main()
{
printf("Enter the expression: ");
yyparse();
}
DIGIT [0-9]+\.?|[0-9]*\.[0-9]+
%%
[ ]
{DIGIT} {yylval=atof(yytext);return NUM;}
\n|. {return yytext[0];}
// Yacc file: desk.y
%{
#include<ctype.h>
#include<stdio.h>
#define YYSTYPE double
%}
%token NUM
%left '+' '-'
%left '*' '/'
%right UMINUS
%%
S : S E '\n' { printf("Answer: %g \nEnter:\n", $2); }
| S '\n'
|
| error '\n' { yyerror("Error: Enter once more...\n" );yyerrok; }
;
E : E '+' E { $$ = $1 + $3; }
| E'-'E { $$=$1-$3; }
| E'*'E { $$=$1*$3; }
| E'/'E { $$=$1/$3; }
| '('E')' { $$=$2; }
| '-'E %prec UMINUS { $$= -$2; }
| NUM
;
%%
#include "lex.yy.c"
int main()
{
printf("Enter the expression: ");
yyparse();
}
Comments
Post a Comment