计算没有评论行的lex计划

时间:2017-11-10 17:57:07

标签: c flex-lexer lex lexer

此处程序计算注释行,单行注释和多行注释的编号,并以file.txt作为输入给出总注释输出

file.txt

//hellow world
/*hello world1*/
/*hello world2
*/
/*hello world3
hello world3.1*/
#include<>

count.l

    %{
    #include<stdio.h>
    #include<stdlib.h>
    int a=0,b=0,c=0,d;
%}
%%
"//".* {a++;}
"/*" {b++;}
.*"*/" {b--;c++;}
%%
void main(int argc,char *argv[]){
    yyin=fopen(argv[1],"r");
    yylex();
    printf("single line %d \nmultiline %d \n",a,c);
    d=a+c;
    printf("total %d \n",d);
}

这里输出的是

./ a.out file.txt

hello world2 

hello world3



#include<>
single line 1 
multiline 3 
total 4 

我需要获得的输出只是

#include<>
single line 1 
multiline 3 
total 4 

我也尝试过这种方式,我添加.* "/*"前面"/*".*这样"*/"然后它会删除该行中的BackendServiceModule并给我多行注释计数为2。 我试过各种各样的方式,但我有点卡住了。

3 个答案:

答案 0 :(得分:2)

添加了精确的逻辑,使其更好地运作。

    %{
    #include<stdio.h>
    #include<stdlib.h>
    int a=0,c=0,d,e=0;
%}
%%
"/*" {if(e==0)e++;}
"*/" {if(e==1)e=0;c++;}
"//".* {if(e==0)a++;}
. {if(e==0)ECHO;}
%%
void main(int argc,char *argv[]){
    yyin=fopen(argv[1],"r");
    yyout=fopen(argv[2],"w");
    yylex();
    printf("single line %d \nmultiline %d \n",a,c);
    d=a+c;
    printf("total %d \n",d);
}

答案 1 :(得分:2)

这就是启动状态的用途 - 它们允许您为不同的状态定义不同的匹配规则:

%{
#include<stdio.h>
#include<stdlib.h>
int a=0,b=0,c=0,d;
%}
%x COMMENT    /* an exclusive state that does not also match normal stuff */
%%
"//".*   {a++;}
"/*"     { BEGIN COMMENT; }
<COMMENT>"*/" {c++; BEGIN INITIAL; }
<COMMENT>.    ;
%%
void main(int argc,char *argv[]){
    yyin=fopen(argv[1],"r");
    yylex();
    printf("single line %d \nmultiline %d \n",a,c);
    d=a+c;
    printf("total %d \n",d);
}

这将适当处理

之类的事情
/*  //  */  ..this is not a comment..

这会混淆大多数尝试这样做的其他方式。它还会继续输出评论中的换行符(因此muliline /../评论将显示为空行。如果您不想要,则可以为{添加规则] {1}}

答案 2 :(得分:0)

%{
    #include<stdio.h>
    #include<stdlib.h>
    int a=0,b=0,d;
%}
%%
"//".* {a++;}
[/][*][^*]*[*]+([^*/][^*]*[*]+)*[/] {b++;}

%%
void main(int argc,char *argv[]){
    yyin=fopen(argv[1],"r");
    yylex();
    printf("single line %d \nmultiline %d \n",a,b);
    d=a+b;
    printf("total %d \n",d);
}

.与其他所有内容相匹配。这样就可以了。

同样如您的回答所指出,您刚刚使用.打印了其余字符。