^D does not work in yylex() function
I know the basics of flex
%{
#include<stdio.h>
int c=0;
int blank=0;
int line=0;
int word=0;
%}
%%
([a-zA-z])+(" "|\n) {word++; int i=0;
while(yytext[i]!='\0')
{
if(yytext[i]=' ') blank++;
else if(yytext[i]=='\n') line++;
}
}
" " {blank++; c++;}
\n {line++; c++;}
. {c++;}
%%
int main()
{
yylex();
printf("The no of characters is %d\n",c);
printf("The no of blanks is %d\n",blank);
printf("The no of lines is %d\n",line);
printf("The no of words is %d\n",word);
}
I tried a lot but could not think of anything . Please help I am stuck on this.
This whole section of code makes absolutely no sense. You're looking for a series of letters followed by a space or newline and then doing a while loop to see when the first character (you never change the value of i
) in yytext
is equal to a string that happens to be empty?
([a-zA-z])+(" "|\n) {word++; int i=0;
while(yytext[i]!="\0")
{
if(yytext[i]=" ") blank++;
else if(yytext[i]=="\n") line++;
}
}
If you're looking for the NUL terminating character you need to specify it as a character not put it in double quotes. And you also need to increment i
so that you'll traverse the whole of yytext
. As it currently stands, your while
loop will never terminate, which explains why ^D isn't doing anything. But you don't need to do any of that.
Since all you're after is counting how many words there are, all you need to do is...
([a-zA-z])+ {word++;}
... since the other rules will handle counting spaces and newlines etc...