문제

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