質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top