C向C++的注释的转换

来源:互联网 发布:sqlserver视频教程 编辑:程序博客网 时间:2024/05/20 16:43

若想完成C注释向C++注释的转换:首先要识别注释语言的种类,例如://hello 是C++的注释标准,/*hello*/是C的注释标准,转换的过程就是指针指向的如果是相邻的// 则·照常输入·,如果·遇见换行,则进入普通状态,重新对下一个字符进行判断。

如果遇见相邻的/*则需要进行C注释向C++注释的转换,即/*—>//的转换,C注释的开头标志转换成//之后,再需要进行注释标志结尾的查找,如果找到两个相邻的*/(如:*/,*****/等情况),(注意注释结束要输入换行),则表示C注释的结束,则之后进入普通状态,对下一个字符进行判断。

如果遇见普通的代码,则照常输出。

具体的代码如下:

      头文件:connvert_comment.h

#ifndef __CONNVERT_COMMENT_H__#define __CONNVERT_COMMENT_H__#define INTPUTFILE "intput.c"#define OUTPUTFILE "output.c"enum {CSTATUS,NULLSTATUS,CPPSTATUS,EOFSTATUS};void do_null_status(FILE *ifp,FILE *ofp);void do_cpp_status(FILE *ifp,FILE *ofp);void do_cs_status(FILE *ifp,FILE *ofp);void do_eof_status(FILE *ifp,FILE *ofp);static void convert_work(FILE *ifp,FILE *ofp);void connver_main();#endif
源文件 main.c

#include<stdio.h>#pragma warning(disable:4996)#include<windows.h>#include"connvert_comment.h"int main(void){connver_main();system("pause");return 0;}

源文件 connvert_comment.c

#include<stdio.h>#include<stdlib.h>#pragma warning (disable:4996)#include"connvert_comment.h"int status=NULLSTATUS;void do_null_status(FILE *ifp,FILE *ofp){ int c=fgetc(ifp);if(c=='/'){int s=fgetc(ifp);     if(s=='*') { fputc('/',ofp); fputc('/',ofp); status=CSTATUS; } else if(s=='/') { fputc('/',ofp); fputc('/',ofp); status=CPPSTATUS; } else if(s==EOF) { status=EOFSTATUS; } else { fputc(c,ofp); }}else  if(c==EOF){   status=EOFSTATUS;}else if(c=='\n'){fputc('\n',ofp);status=NULLSTATUS;}else{fputc(c,ofp);}}
void do_cs_status(FILE *ifp,FILE *ofp){ int c=fgetc(ifp); if(c=='*'){int s=fgetc(ifp);if(s=='/'){ status=NULLSTATUS;}else if(s=='\n'){fputc('\n',ofp);fputc('/',ofp);fputc('/',ofp);}else{ungetc(s,ifp);  fputc(c,ofp);}}else if(c=='\n'){fputc('\n',ofp);fputc('/',ofp);fputc('/',ofp);}else  fputc(c,ofp);}


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_cs_status(ifp,ofp);break;default:break;}}}void connver_main(){FILE * ifp=fopen(INTPUTFILE,"r");FILE * ofp=fopen(OUTPUTFILE,"w");if(ifp==NULL ||ofp==NULL){printf("");return ;}convert_work(ifp,ofp);fclose(ifp);fclose(ofp);return;}




原创粉丝点击