Creating a simple calculator using flex program

Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.


Code:

 % {

  int op = 0,i;
  float a, b;
% }
  
dig [0-9]+|([0-9]*)"."([0-9]+)
add "+"
sub "-"
mul "*"
div "/"
pow "^"
ln \n
%%
  
/* digi() is a user defined function */
{dig} {digi();} 
{add} {op=1;}
{sub} {op=2;}
{mul} {op=3;}
{div} {op=4;}
{ln} {printf("\n The Answer :%f\n\n",a);}
  
%%
digi()
{
 if(op==0)
  
/* atof() is used to convert 
      - the ASCII input to float */
 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;
 }
}
  
main(int argv,char *argc[])
{
 yylex();
}
  
yywrap()
 {
  return 1;
 }

Post a Comment

Previous Post Next Post