Lex Program to recognize and count the number of keywords in a given input file
Problem definition:
Write a Lex program to recognize the keywords in a given input file, count them, and display the result on standard output.
Structure of LEX Program:
| %{ Definition section %} %% Rules section %% User Subroutine section |
Click here to learn – How to Compile & Run LEX / YACC Programs on Windows 8, 10, and 11?
Source Code – Lex Program to recognize and count the number of keywords
%{
#include<stdio.h>
#include<string.h>
int count_key=0;
%}
%%
int |
float |
char |
double |
switch |
if |
while |
do { count_key++;}
.|\n {;}
%%
int main ( int argc,char *argv[] )
{
if(argc==2)
yyin=fopen(argv[1],"r");
else
{
printf("\nEnter the input:\n");
yyin=stdin;
}
yylex();
printf("\nNumber of keywords = %d\n",count_key);
}
int yywrap( )
{
return 1;
}Output:
input.c is the input file for the program
void main()
{
int a; // integer variable
float b; /* float variable */
/* Multiline
Comment */
fun(); // function call
}maheshgh@maheshgh:~/LexYacc$ lex demo.l
maheshgh@maheshgh:~/LexYacc$ gcc lex.yy.c
maheshgh@maheshgh:~/LexYacc$ ./a.out input.c
Number of keywords = 4
Summary:
This article discusses how to Write a Lex program to recognize the keywords in a given input file, count them, and display the result on standard output. If you like the article, do share it with your friends.
