对于代码来说注释是非常重要的,因为这样可以提高自己写的代码的刻度性,现在实现c转换成c++注释的功能,可以将眼花缭乱的注释方式总结成8个种类,分别是:

// 1.一般情况

/* int i = 0; */


// 2.换行问题

/* int i = 0; */int j = 0;

/* int i = 0; */

int j = 0;


// 3.匹配问题

/*int i = 0;/*xxxxx*/


// 4.多行注释问题

/*

int i=0;

int j = 0;

int k = 0;

*/int k = 0;


// 5.连续注释问题

/**//**/


// 6.连续的**/问题

/***/


// 7.C++注释问题

// /*xxxxxxxxxxxx*/


// 8.C注释本身不匹配

/* int i = 0;

对于这8中情况我们可以采用状态机的方式编程,里面设置C_BEGIN,C_END,CPP_BEGIN,CPP_END这几种状态,然后一次性读取两个字符来决定将无状态切换至相应状态。

代码实现:

///////////////////////////////////////////////////////////////////////////////////////

int main()

{

ConvertState ret;

ret=NoteConvert("input.c","output.c");

if (ret == SUCCESS)

{

printf("转换成功\n");

}

else if (ret == FAIL)

{

printf("转换失败\n");

}

else

{

printf("不匹配\n");

}

system("pause");

return 0;

}

////////////////////////////////////////////////////////////////////////////////////////


#pragma once//保证只被编译一次

#include <stdio.h>

#include <errno.h>

typedef enum ConvertState

{

SUCCESS,

FAIL,

NO_MATCH,

}ConvertState;

typedef enum State

{

C_BEGAIN,

C_END,

CPP_BEGAIN,

CPP_END,

}State;

ConvertState Convert(FILE *fIn, FILE *fOut)

{

ConvertState ret=SUCCESS;

State tag = C_END;

char first;

char second='a';

do{

first = fgetc(fIn);

switch (first)

{

case '/':

second = fgetc(fIn);

if (second == '*')

{

if (tag == C_END)

{

fputc('/', fOut);//1.一般问题

fputc('/', fOut);

tag = C_BEGAIN;//3.匹配问题

}

else

{

fputc('/', fOut);

fputc('*', fOut);

}

}

else if (second == '/')//7.c++注释问题   // /*xxxxxxxxxxxx*/

{

char nextNEXT;

fputc('/', fOut);

fputc('/', fOut);

tag = CPP_BEGAIN;

do{

nextNEXT = fgetc(fIn);

fputc(nextNEXT, fOut);

} while (nextNEXT != '\n'&&nextNEXT != EOF);

tag = CPP_END;

}

break;

case'\n'://4.多行注释问题

if (tag == C_BEGAIN)

{

fputc('\n', fOut);

fputc('/', fOut);

fputc('/', fOut);

}

else

{

fputc('\n', fOut);

}

break;

case '*':

second = fgetc(fIn);

if (second == '/')

{

char next=fgetc(fIn);

if (next == '/')// 5.连续注释问题/**//**/

{

fputc('\n', fOut);

fseek(fIn, -1, SEEK_CUR);

}

else if (next != '\n'&&next!=EOF)//2.换行问题

{

fputc('\n', fOut);

fputc(next, fOut);

}

else

{

fputc('\n', fOut);

}

tag = C_END;

}

else if (second == '*')// 6.连续的**/问题 /***/

{

fputc(first, fOut);

fseek(fIn, -1, SEEK_CUR);

}

else

{

fputc(first, fOut);

fputc(second, fOut);

}

break;

default:

fputc(first, fOut);

break;

}

} while (first != EOF);

if (ret != C_END)

{

ret = NO_MATCH;

}

return ret;

}

ConvertState NoteConvert(char *inputFile, char *outputFile)

{

ConvertState ret;

FILE *fIn = fopen(inputFile, "r");

FILE *fOut = fopen(outputFile, "w");

if (fIn == NULL)

{

printf("打开文件失败\n");

printf("errno:%d\n",errno);

perror("perror says open failed");

return;

}

if(fOut== NULL)

{

fclose(fIn);

printf("打开文件失败\n");

perror("perror says open failed");

return;

}

ret=Convert(fIn,fOut);

fclose(fIn);

fclose(fOut);  

}

这种方式称为状态机编程,对于有很多情况且比较混乱的情况是可以采用这种方式。