【发布时间】:2014-03-09 08:53:27
【问题描述】:
谁能帮助我编写一个 LEX 程序来检查和计算 C 程序中的注释行。到处找了,没得到完整的代码。
【问题讨论】:
标签: lex
谁能帮助我编写一个 LEX 程序来检查和计算 C 程序中的注释行。到处找了,没得到完整的代码。
【问题讨论】:
标签: lex
注释行的格式为
%% {START} {无论符号、字母数字和字母} {END} %%
这是一个示例代码
`
%{
#include<stdio.h>
int c=0;
%}
START "/*"
END "*/"
SIMPLE [^*]
SPACE [ \t\n]
COMPLEX "*"[^/]
%s newstate
%%
"//"(.*[ \t]*.*)*[\n]+ {c++; fprintf(yyout," ");}
{START} {yymore();BEGIN newstate;}
<newstate>{SIMPLE} {yymore();BEGIN newstate;}
<newstate>{COMPLEX} {yymore();BEGIN newstate;}
<newstate>{SPACE} {yymore();BEGIN newstate;}
<newstate>{END} {c++;fprintf(yyout," ");BEGIN 0;}
%%
main()
{//program to remove comment lines
yyin=fopen("file4","r");
yyout=fopen("fileout4","w");system("cat file4");
yylex();system("cat fileout4");
printf("no.of comments=%d",c);
fclose(yyin);
fclose(yyout);
}
`
输入文件“file4”在下面
/* #include <stdlib.h>
{}.@All nonsense symbols */
//another comment
int main{}
{/**/
printf("hello");
/* comment inside// comment is ignored */
//how about//this?
/* now we /* try this */ */
printf("COOL!!");
return (0);
}
它给出了存储在“fileout4”中的以下输出`
int main{}
{
printf("hello");
*/
printf("COOL!!");
return (0);
}
`
上述程序中的注释行数为6。
【讨论】:
/** 1 /** 2 **/ 3 **/,那么你的输出是什么?
您可以维护一个 boolean 变量来跟踪您正在解析的行是否在多行注释内。
%{
#include <stdio.h>
#include <stdbool.h>
int comment_lines = 0;
bool in_comment = false;
%}
%%
"/*".*\n { in_comment = true; ++comment_lines; }
.*"*/"\n { in_comment = false; ++comment_lines; }
"//".*\n { ++comment_lines; }
.*\n {
if (in_comment) {
++comment_lines;
} else {
fprintf(yyout, yytext);
}
}
%%
int yywrap() {
return 1;
}
int main(void) {
printf("Enter input file: ");
char filename[64];
scanf("%s", filename);
yyin = fopen(filename, "r");
printf("Enter output file: ");
scanf("%s", filename);
yyout = fopen(filename, "w");
yylex();
printf("Number of comments: %d\n", comment_lines);
}
在上面的代码中,in_comment 用于表示正在分析的行的状态。如果在注释中,则增加comment_lines 的值,否则将文本写入yyout 给出的输出文件。
输入文件
#include <stdio.h>
/*
*
* This is a multi-line comment
*
*/
void dummy();
// main function is the entry point.
int main(void) {
/*
* Here we print a message on user's
* console.
*/
printf("Hello world\n");
// That is it.
}
输出文件在词法分析后生成
#include <stdio.h>
void dummy();
int main(void) {
printf("Hello world\n");
}
Number of comments: 11
【讨论】:
%{
#undef yywrap
#define yywrap() 1
int single=0, multiline =0;
%}
%%
"//".*"\n" {printf("%s\n", yytext); single++;}
"/*".*[\n]*.*"*/" {printf("%s\n", yytext); multiline++;}
.;
%%
int main()
{
yyin = fopen("yourfile","r");
yylex(); //calling the rules section
printf(" Single line comments = %d, multiline comments = %d", single, multiline);
fclose(yyin);
}
【讨论】: