Skip to content

Instantly share code, notes, and snippets.

@LeslieZhu
Last active January 2, 2016 00:09
Show Gist options
  • Save LeslieZhu/8221901 to your computer and use it in GitHub Desktop.
Save LeslieZhu/8221901 to your computer and use it in GitHub Desktop.
一个Lex文件,通过flex upper-comment.lex; gcc lex.yy.c -o upper-comment;生成一个C语言程序,用于将C语言中注释内的字符转换为大写,是《编译原理及实践》习题2.22。 参考了info flex文档里面给出的例子,增加对“//”注释的支持,是lex中基础知识内容。
%option noyywrap
%%
"/*" ECHO;{
register int c,prev_c;
for ( ; ; ){
while ( (c = input()) != '*' && c != EOF ){
printf("%c",toupper(c));
}
if ( c == '*' ){
printf("%c",c);
prev_c = c;
while ( prev_c == '*' && (c = input()) != '/' ){
printf("%c",toupper(c));
prev_c = c;
break;
}
if ( c == '/' ){
printf("/");
break; /* found the end */
}
}
if ( c == EOF ){
error( "EOF in comment" );
break;
}
}
}
"//" ECHO;{
register int c;
for ( ; ; ){
while ( (c = input()) != '\n' && c != EOF ){
printf("%c",toupper(c));
}
if(c == '\n'){
printf("\n");
break;
}
if ( c == EOF ) {
error( "EOF in comment" );
break;
}
}
}
%%
void main(){
yylex();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment