/********************************************************************
*删除C/C++注释
**********************************************************************/
#include <stdio.h>
//注意
//1.对/****/的处理
//2.要保留双引号之间的内容,如char* test = "/*i am not comment */";
//3.对于单引号中的内容同样保留(不检查程序的语法错误)
//4.对于转义字符的处理(见状态6),如char* test = "string/"string too/*i am not comment"
int noComment(FILE *in,FILE *out)
{
int ch, lastch, state = 0, sq = 0;
while( ( ch = fgetc(in) ) != EOF )
{
switch(state)
{
case 0:
if( ch == '/' )
{
lastch = '/' ;
state = 1 ;
}
else
{
if( ch == '/'' || ch == '"' )
{
state = 5 ;
if( ch == '/'' )
sq = 1;
}
fputc(ch, out);
}
break;
case 1:
if( ch == '/' )
state = 2 ;
if( ch == '*' )
state = 3 ;
else
{
state = 0 ;
fputc(lastch, out) ;
fputc(ch, out) ;
}
break ;
case 2: // C++ comment
if( ch == '/n' )
{
state = 0 ;
fputc(ch, out);
}
break;
case 3: // C comment
if( ch == '*' )
state = 4 ;
break ;
case 4:
if( ch == '/' )
state = 0 ;
else if( ch != '*' )
state = 3 ;
break ;
case 5:
if( ch == '/'' && sq == 1)
{ // end of single quotes
state = 0 ;
sq = 0 ;
}
else if( ch == '"' && sq == 0)
{// end of double quotes
state = 0 ;
}
else if( ch == '//' )
{//force to go on with state 5 when enconter '//'
state = 6 ;
}
fputc(ch,out);
break;
case 6://force to go on with state 5 when enconter '//'
state = 5 ;
break;
default:
fprintf(stderr,"encounter an error/n");
}
}
return 1;
}
删除C/C++注释
最新推荐文章于 2023-10-18 15:59:52 发布