开发者

Lex : print line numbers

I have a source code and I would like to add line numbers.

What I've done :

%{
    int lines=0;
%}

LINE \n

%%
{LINE} {ECHO;printf("%d", ++lines);}

However, I don't know 开发者_运维百科how to catch the first line. Can you help me ?


Add the line:

printf("%d", ++lines);

as the first thing in main. Its a hack, but an effective one :)

Edit: The result should look something like this:

%{
    int lines=0;
%}

LINE \n

%%
{LINE} {ECHO;printf("%d", ++lines);}
%%

main()
{
    printf("%d", ++lines);
    yylex();
}

Disclaimer: syntax from a book, not actually compiled. You might have to massage it a little bit.


Try this:

%{
#include<stdio.h>    
int lines=0;
%}


%%
.*\n {printf("%d %s",++lines,yytext);}
%%

int main()
{

yylex();
return 0;
}


%{
int yylineno=0;
%}


%%
^(.*)\n {printf("%4d %s",++yylineno,yytext);
%%

int main(int argc, char **argv)
{
yyin=fopen(argv[1],"r");
yylex();
fclose(yyin);
}


Check to see if your version provides a variable named "yylineno", many of them do.

I know flex 2.6.0 does.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜