1

Whenever I get a token being recognized by a lex program for e.g.

"while"   { printf("%s is a loop\n",yytext);}

I want to collect that token name (i.e while) in another string, that is declared earlier, for e.g.

"while"   { printf("%s is a loop\n",yytext); str = yytext;}

but it doesn't produce the required output when str is being printed in main. It prints whole input from where the token has been recognized to the end of the input. How to copy just the token we have found to another string?

1 Answer 1

1

In C the memory for strings has to be allocated explicitly. The following would work:

    "while" {
            printf("%s is a loop\n",yytext);
            str = malloc(strlen(yytext)+1);
            if (str == NULL) abort();
            strcpy(str,yytext);
     }

Beware that the above code will leak memory if the while keyword occurs more than once in the input.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.