Objective: Write A Lex Program To Implement Simple Calculator Code
Objective: Write A Lex Program To Implement Simple Calculator Code
Objective: Write A Lex Program To Implement Simple Calculator Code
Code:
%option noyywrap
%{
#include<stdio.h>
int op=0,i;
float a,b;
%}
dig [0-9]+|([0-9]*)"."([0-9]+)
add "+"
sub "-"
mul "*"
div "/"
ln "\n"
%%
{dig} {digit();}
{add} {op=1;}
{sub} {op=2;}
{mul} {op=3;}
{div} {op=4;}
{ln} {printf("result is %f\n",a);}
%%
digit()
{
if(op==0)
{
a=atof(yytext);
}
else
{
b=atof(yytext);
switch(op)
{
case 1:a=a+b;
break;
case 2:a=a-b;
break;
case 3:a=a*b;
break;
case 4:a=a/b;
break;
}
op=0;
}
}
void main()
{
yylex();
}
Output:
Questions:
2-What is yywrap?
Ans:Function yywrap is called by lex when input is exhausted. Return 1 if you are done or 0 if more
processing is required.