在一个文件里有一段代码,将里面的 /* */ 注释全部转换为 // 注释,初学者可能听起来很牛很难(我现在是初学者,我是这样认为的),只要理解了问题的意思,就会发现,诶,有点意思
话不多说,直接代码走起
convert_comment.h
#ifndef _CONVERT_COMMENT_H_
#define _CONVER_COMMENT_H_
#define INPUTFILE "input.c"
#define OUTPUTFILE "output.c"
enum{CSTATUS,CPPSTATUS,NULLSTATUS,EOFSTATUS};
void connver_main();
#endifmain.c
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"convert_comment.h"
int main()
{
connver_main();
system("pause");
}convert_comment.c
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"convert_comment.h"
int status = NULLSTATUS;
void do_null_status(FILE* ifp,FILE *ofp)
{
int c = fgetc(ifp);
switch(c)
{
case '/':
{
int s = fgetc(ifp);
switch(s)
{
case '*':
{
fputc('/',ofp);
fputc('/',ofp);
status = CSTATUS;
}
break;
case '/':
fputc('/',ofp);
fputc('/',ofp);
status = CPPSTATUS;
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(c,ofp);
ungetc(s,ifp);//不知道啥东西,退回去
status = NULLSTATUS;
break;
}
}
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(c,ofp);
status = NULLSTATUS;
break;
}
}
void do_cpp_status(FILE* ifp,FILE *ofp)// is //
{
int c = fgetc(ifp);
switch(c)
{
case '\n':
fputc('\n',ofp);
break;
case '/':
status = CPPSTATUS;
break;
case '*':
fputc('/',ofp);
fputc('/',ofp);
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(c,ofp);
status = NULLSTATUS;
break;
}
}
void do_c_status(FILE* ifp,FILE *ofp)// is **
{
int c = fgetc(ifp);
switch(c)
{
case '*':
{
int s = fgetc(ifp);
switch(s)
{
case '/':
fputc('\n',ofp);
status = NULLSTATUS;
break;
default:
fputc(c,ofp);
ungetc(s,ifp);
status = CSTATUS;
break;
}
}
break;
case EOF:
status = EOFSTATUS;
break;
case '\n':
fputc('\n',ofp);
fputc('/',ofp);
fputc('/',ofp);
status = CSTATUS;
break;
default:
fputc(c,ofp);
status = CSTATUS;
break;
}
}
static void convert_work(FILE * ifp,FILE * ofp)
{
while(status != EOFSTATUS)
{
switch( status)
{
case NULLSTATUS:
do_null_status(ifp,ofp);
break;
case CPPSTATUS:
do_cpp_status(ifp,ofp);
break;
case CSTATUS:
do_c_status(ifp,ofp);
break;
case EOFSTATUS:
break;
default:
break;
}
}
}
void connver_main()
{
FILE *ifp = fopen(INPUTFILE,"r");
FILE * ofp = fopen(OUTPUTFILE,"w");
if(ifp == NULL||ofp == NULL)
{
fprintf(stderr,"this is fopen error\n");
return ;
}
convert_work(ifp,ofp);
fclose(ifp);
fclose(ofp);
}
不要忘了要把 input.c output.c文件建立在和你main.c comment.c .h文件一样的位置哦!
如果有不对的地方,可以评论告诉我,望指导!

被折叠的 条评论
为什么被折叠?



