此篇博客主要写如何将c风格注释(/*xxx*/)转换为c++风格注释(//xxx).
下图即为注释转换的过程图:
#include<stdio.h>
typedef enum State
{
Normal,
FOUND_SLAH,//找到/
CPP_State,
C_State,
FOUND_START//找到*
}State;
int main()
{
FILE* input = fopen("input.c","r");
if (input == NULL) {
perror("");
return 0;
}
FILE* output = fopen("output.c", "w");
if (output == NULL){
perror("");
return 0;
}
State state = Normal;
int ch, nextch;
while (1)
{
ch = fgetc(input);
if (ch == EOF)
{
break;
}
switch (state)
{
case Normal:
if (ch == '/')
{
fputc(ch, output);
state = FOUND_SLAH;
}
else
{
fputc(ch, output);
state = Normal;
}
break;
case CPP_State:
if (ch == '\n')
{
fputc(ch, output);
state = Normal;
}
else
{
fputc(ch, output);
state = CPP_State;
}
break;
case FOUND_SLAH:
//fputc(ch, output);
if (ch == '/')
{
fputc(ch, output);
state = CPP_State;
}
else if (ch == '*')
{
//nextch = ch;
fputc('/', output);
state = C_State;
}
else {
fputc(ch, output);
state = Normal;
}
break;
case C_State:
if (ch == '*')
{
state = FOUND_START;
}
if (ch != '*')
{
fputc(ch, output);
if (ch == '\n')
{
fprintf(output,"//");
}
state = C_State;
}
break;
case FOUND_START:
if (ch == '*') {
fputc('*', output);
state = FOUND_START;
}
else if (ch == '/')
//注释转换后回到普通模式
/* hello */
{
nextch = fgetc(input);
if (nextch != '\n')
fputc('\n', output);
ungetc(nextch,input);
state = Normal;
}
else {
// *之后没有/回到C风格
fputc('*', output);
fputc(ch, output);
state = C_State;
}
break;
}
}
fclose(input);
fclose(output);
return 0;
}
测试代码:
// 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*/
转换结果:
// 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*/