c语言项目—注释转换(c——c++)
题目要求:
要将全部的c语言风格的注释转换为c++风格的注释,如下图所示,需要将input.c文件经过注释转换程序转换为output.c文件所示。
这是测试结果:
首先我们来分析一下这个题目,在做这个项目时,我们需要引进有限状态机这个概念。那我们先来了解一下什么是有限状态机。
有限状态机FSM是软件上一种常用的处理方法,他把复杂的控制逻辑分成有限个稳定状态,在每个状态上进行处理。
我们来画一下状态图:
所以我们把这个项目分成这几个状态。
NUL_STATE,C_STATE,CPP_STATE,EMD_STATE
现在我们来实现一下这个项目。
"CommentConvert.h"
#ifndef__COMMENT_CONVERT_H__#define__COMMENT_CONVERT_H__#include<stdio.h>#include<stdlib.h>#defineINPUTFILENAME"input.c"#defineOUTPUTFILENAME"output.c"enumSTATE{NUL_STATE,C_STATE,CPP_STATE,EMD_STATE};voidCommentConvert(FILE*pRead,FILE*pWrite);voiddo_nul_state(FILE*pRead,FILE*pWrite);voiddo_c_state(FILE*pRead,FILE*pWrite);voiddo_cpp_state(FILE*pRead,FILE*pWrite);#endif//__COMMENT_CONVERT_H__
"CommentConvert.c"
#include"CommentConvert.h"enumSTATEstate;voidCommentConvert(FILE*pRead,FILE*pWrite){while(state!=EMD_STATE){switch(state){caseNUL_STATE:do_nul_state(pRead,pWrite);break;caseC_STATE:do_c_state(pRead,pWrite);break;caseCPP_STATE:do_cpp_state(pRead,pWrite);break;caseEMD_STATE:break;}}}voiddo_nul_state(FILE*pRead,FILE*pWrite){intfirst=0;intsecond=0;first=fgetc(pRead);switch(first){case'/':{second=fgetc(pRead);if(second=='*'){fputc('/',pWrite);fputc('/',pWrite);state=C_STATE;}elseif(second=='/'){fputc(first,pWrite);fputc(second,pWrite);state=CPP_STATE;}else{fputc(first,pWrite);fputc(second,pWrite);}}break;caseEOF:state=EMD_STATE;break;default:fputc(first,pWrite);break;}}voiddo_c_state(FILE*pRead,FILE*pWrite){intfirst=0;intsecond=0;intthird=0;first=fgetc(pRead);switch(first){case'*':{second=fgetc(pRead);switch(second){case'/':third=fgetc(pRead);if(third!='\n'){fputc('\n',pWrite);//fputc('/',pWrite);//fputc('/',pWrite);state=CPP_STATE;}if(third=='/'){ungetc(third,pRead);state=NUL_STATE;break;}else{fputc(third,pWrite);state=NUL_STATE;break;}case'*':third=fgetc(pRead);fputc(first,pWrite);if(third=='/'){state=NUL_STATE;}break;default:fputc(first,pWrite);fputc(second,pWrite);break;}break;case'\n':fputc(first,pWrite);fputc('/',pWrite);fputc('/',pWrite);break;caseEOF:state=EMD_STATE;break;default:fputc(first,pWrite);break;}}}voiddo_cpp_state(FILE*pRead,FILE*pWrite){intfirst=0;first=fgetc(pRead);switch(first){case'\n':{fputc(first,pWrite);//fputc('/',pWrite);//fputc('/',pWrite);state=NUL_STATE;}break;caseEOF:state=EMD_STATE;break;default:fputc(first,pWrite);break;}}
“test.c”
#include"CommentConvert.h"intmain(){FILE*pRead=NULL;FILE*pWrite=NULL;printf("注释转换开始:");pRead=fopen(INPUTFILENAME,"r");if(NULL==pRead){perror("openfileforread\n");exit(EXIT_FAILURE);}pWrite=fopen(OUTPUTFILENAME,"w");if(NULL==pWrite){fclose(pRead);perror("openfileforwrite\n");exit(EXIT_FAILURE);}CommentConvert(pRead,pWrite);printf("注释转换完成:");return0;}
这样就完成了注释转换项目。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。