Objective: Write A Lex Program To Implement Simple Calculator Code

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Objective: Write a lex program to implement simple calculator

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:

1- What is the full form of atof?


Ans: atof is a function in the C programming language that converts a string into a floating point
numerical representation. atof stands for ASCII to float. It is included in the C standard library header
file stdlib.h

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.

You might also like