Question

I am trying to find the longest word that is composed of alphabets [ghijklpqrswxyz].. This seemed like a simple problem, but I guess I have some trouble understanding how lex/yaac works. I'm testing this with a linux /usr/share/dict/words file, and the program simple returns the whole list of words instead of printing the longest one..

% lex example.l
% cc lex.yy.c -ll
% ./a.out < /usr/share/dict/words

What seems to be the problem??

%{
char* longest="";
%}

%option noyywrap

%%
^[ghijklpqrswxyz]+$    {if (strlen(yytext)>strlen(longest)) {longest = yytext;}}
.|\n    {;}
%%

int main(void)
{
    yylex();
    printf("The longest matching word: %s\n", longest);
    return 0;
}

No correct solution

OTHER TIPS

The value of yytext gets overwritten. You will need to duplicate and copy the value rather than simply assigning it:

longest = malloc(sizeof(char)*strlen(yytext)); strcpy(longest, yytext);

Keep in mind that you will want to cleanup (free) successive values of longest. But be careful to not free the statically assigned value longest = ""; !

This program is the corrected version of your program. It runs accurately.

%option noyywrap
%{
char* longest="";
%}
%%
[a-zA-Z]* {if(strlen(yytext)>strlen(longest)) longest = malloc(sizeof(char)*strlen(yytext)); strcpy(longest, yytext);}
%%
int main(void)
{
yylex();
printf("The longest matching word: %s\n", longest);
return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top