Lex Program to count the numbers of lines, words, spaces, and characters in a given statement
Problem definition:
Write a lex program to recognize lines, words, spaces, and characters in a given statement and display the numbers of lines, words, spaces, and characters on standard output.
Structure of LEX Program:
| %{ Definition section %} %% Rules section %% User Subroutine section |
Click here to know – How to Compile & Run LEX / YACC Programs on Windows 8, 10, and 11?
Source Code to count the numbers of lines, words, spaces, and characters in a given statement
/*Lex Program to count numbers of lines, words, spaces and characters
in a given statement*/
%{
#include<stdio.h>
int sc=0,wc=0,lc=0,cc=0;
%}
%%
[\n] { lc++; cc+=yyleng;}
[ \t] { sc++; cc+=yyleng;}
[^\t\n ]+ { wc++; cc+=yyleng;}
%%
int main(int argc ,char* argv[ ])
{
printf("Enter the input:\n");
yylex();
printf("The number of lines=%d\n",lc);
printf("The number of spaces=%d\n",sc);
printf("The number of words=%d\n",wc);
printf("The number of characters are=%d\n",cc);
}
int yywrap( )
{
return 1;
}Output:
maheshgh@maheshgh:~/LexYacc$ lex demo.l
maheshgh@maheshgh:~/LexYacc$ gcc lex.yy.c
maheshgh@maheshgh:~/LexYacc$ ./a.out
Enter the input: Greetings from VTUPulse.com
Welcome to VTUPulse.com
Lex Yacc Tutorial
(Note: After input string press enter and ctrl+d)
The number of lines=3
The number of spaces=6
The number of words=9
The number of characters are=70
Program to count the numbers of lines, words, spaces, and characters from a given file
%{
#include<stdio.h>
int sc=0,wc=0,lc=0,cc=0;
%}
%%
[\n] { lc++; cc+=yyleng;}
[ \t] { sc++; cc+=yyleng;}
[^\t\n ]+ { wc++; cc+=yyleng;}
%%
int main(int argc ,char* argv[])
{
if(argc==2)
{
yyin=fopen(argv[1],"r");
}
else
{
printf("Enter the input\n");
yyin=stdin;
}
yylex();
printf("The number of lines=%d\n",lc);
printf("The number of spaces=%d\n",sc);
printf("The number of words=%d\n",wc);
printf("The number of characters are=%d\n",cc);
}
int yywrap( )
{
return 1;
}Output:
maheshgh@maheshgh:~/LexYacc$ lex demo.l
maheshgh@maheshgh:~/LexYacc$ gcc lex.yy.c
maheshgh@maheshgh:~/LexYacc$ ./a.out input.txt
(Note: input.txt is the input file containing input text)
The number of lines=3
The number of spaces=6
The number of words=9
The number of characters are=70
Summary:
This article discusses how to write a Lex Program to find and display the number of count numbers of lines, words, spaces, and characters. If you like the article, do share it with your friends.
