LEX- yylineno 返回 1

LEX- yylineno returning 1

我尝试了很多网上给出的解决方案。我尝试过的解决方案之一来自这个link:Flex yylineno set to 1

但是其中 none 似乎适用于我生成符号的代码 table。 yylineno 值不变。它一直显示 1

我在输入文件中提供的输入是:

main()

while

varrrr

if

This is my code snippet:

%%

{pound}{includekey}{openarrow}{alpha}+{closearrow}              
{printf("\n %s : Preprocessor Directive at line no: %d!", yytext, yylineno); newfunction(yytext,"Preprocessor",yyleng);}

{mainkey}{openpara}{closepara}                          {printf("\n %s : Main function found at line no: %d! ", yytext, yylineno); newfunction(yytext,"main",yyleng);}

{alpha}[{underkey}|{alpha}|{digit}]+{openpara}{closepara}           {printf("\n %s : Userdefined function without parameters found at line no: %d!", yytext, yylineno);newfunction(yytext, "function",yyleng);}

{conditional}                                   {printf("\n %s : If statement encountered at line no: %d!", yytext, yylineno);newfunction(yytext,"if", yyleng);}

{control}                                   {printf("\n %s : Control statement encountered at line no: %d!", yytext, yylineno);newfunction(yytext,"control", yyleng);}

{datatypes}                                 {printf("\n %s : Datatype found at line no: %d!", yytext, yylineno);newfunction(yytext, "datatype", yyleng);}

{alpha}*                                    {printf("\n %s : Variable found at line no: %d!", yytext, yylineno);newfunction(yytext, "variable", yyleng);}

{operators}                                 {printf("\n Operator %s found at line no: %d!", yytext, yylineno );}

\n                                      { }

.                                       {printf("\n Unexpected character!");}


%%

此外,我说的是 lex,而不是 yacc。虽然类似,但我试过了yylineno has always the same value in yacc file 但解决方案对我不起作用!

其他问题表明 Flex 能够通过 %option yylineno 指令自动管理 yylineno。然而,与经典 Lex 相比,Flex 是一个扩展。

假设您无法升级到 Flex, 您可能需要更换您的规则

\n { }

\n { yylineno++; }

顺便说一句,在格式字符串末尾使用换行符打印效果最好。当换行符为 'printed' 时,缓冲输出通常会被刷新——因此输出不一定会出现,直到您在其后打印换行符。计划在格式字符串的末尾写换行符,除非你有一个不完整的行。仅当您需要加倍 space 输出时才需要在开头换行(或者您担心其他人草率地用换行符结束输出)。