在编译中,可以用/* */即C风格注释,也可以用//即C++风格注释,本篇博客是将C注释风格转化为C风格注释。
首先:了解C风格和C++风格注释过程
有5中状态,分别是正常代码,遇到*,遇到反斜杠,c风格注释,c++注释风格。
文件input.c为:
/ 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*/
转换代码如下:
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
enum State
{
NORMAL, //普通
FOUND_SLASH, //找到'/'
C_COMMENT, //C风格 注释
CPP_COMMENT, //C++风格注释
FOUND_ASTERISK //找到*
};
CommentConvert(FILE *pIn, FILE * pOut)
{
enum State state = NORMAL;
char ch,nextch;
while (1)
{
ch = fgetc(pIn);
if (ch == EOF)
break;
switch (state)
{
case NORMAL:
if (ch == '/')
state = FOUND_SLASH;
else
{
// 如果不是/ 可以直接输出
state = NORMAL;
fputc(ch, pOut);
}
break;
case FOUND_SLASH:
if (ch == '*')
{
// /*是C注释风格,直接打印//
fprintf(pOut, "//");
state = C_COMMENT;
}
else if (ch == '/')
{
// 两个//说明是C++注释风格
fprintf(pOut, "//");
state = CPP_COMMENT;
}
else // 比如5/3
{
fputc('/', pOut); //首先需要将/输出
fputc(ch, pOut); //再输出3
state = NORMAL;
}
break;
case C_COMMENT:
if (ch == '*') // /* abc */
state = FOUND_ASTERISK;
else
{
fputc(ch, pOut);
if (ch == '\n')// c风格多行注释
fprintf(pOut, "//");
state = C_COMMENT;
}
break;
case FOUND_ASTERISK:
if (ch == '*')
{ //第二次为*,需要将前一个*输出
fputc('*', pOut);
state = FOUND_ASTERISK;
}
else if (ch == '/')
{ // 存在 /* abcd */ int a;换成c++注释风格后,需要判断*/ 后是否为换行
//若不是换行,需要输出\n,否则变成// abcd int a;把int a也注释了
//若是换行,需要将nextch重新放进去
nextch = fgetc(pIn);
if (nextch != '\n')
fputc('\n', pOut);
ungetc(nextch, pIn);
state = NORMAL;
}
else
{ // 如 /*abcd*efg*/ d后的*需要输出再输出e
fputc('*', pOut);
fputc(ch, pOut);
state = C_COMMENT;
}
break;
case CPP_COMMENT:
if (ch == '\n')
{
fputc(ch, pOut);
state = NORMAL;
}
else
{ //不是\n,就输出
fputc(ch, pOut);
state = CPP_COMMENT;
}
break;
}
const char *massage[] =
{
"普通",
"找到反斜杠",
"C风格注释",
"C++风格注释",
"找到*"
};
printf("当前字符:%c,当前状态是:%s\n", ch, massage[state]);
}
}
int main()
{
const char *input = "input.c";
const char *output = "output.c";
FILE *pIn = fopen(input, "r");
assert(pIn);
FILE *pOut = fopen(output, "w");
assert(pOut);
CommentConvert(pIn, pOut);
fclose(pOut);//后打开的先关
fclose(pIn);
system("pause");
return 0;
}
将c风格转为c++风格后为:
文件output.c为:
// 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*/