Number of lines, words and characters using LEX Tool
Aim
Write a lex program to display the number of lines, words and characters in a given input.
Program
Using realtime input
%{
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int cc=0,ws=0,nl=0,nw=0;
%}
%%
[a-zA-Z0-9]+ {nw++;cc+=yyleng;}
[ \t] {ws++;cc++;}
[\n] {nl++;}
%%
int yywrap()
{
return 1;
}
void main()
{
printf("Enter the string for lexical analysys.\n");
yylex();
printf("The number of characters are %d\n",cc);
printf("The number of words are %d\n",nw);
printf("The number of whitespaces are %d\n",ws);
printf("The number of lines are %d\n",nl);
}
Using file
%{
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int cc=0,wc=0,wsc=0,lc=0;
%}
%%
[a-zA-Z0-9]+ {wc++;cc+=yyleng;}
[ \t] {wsc++;cc++;}
[\n] {lc++;}
%%
int yywrap()
{
return 1;
}
void main()
{
yyin = fopen("input.txt","r");
yylex();
printf("The number of charaters are %d: \n",cc);
printf("The number of whitespaces are %d: \n",wsc);
printf("The number of words are %d: \n",wc);
printf("The number of lines are %d: \n",lc);
}
Input
using file
This is a string
to test the lex
program