// 1.一般情况
/* int i = 0; */
// 2.换行问题
/* int i = 0; */int m = 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<iostream>
#include<assert.h>
using namespace std;
typedef enum STATE
{
C_BEGIN, //在c注释段内
C_END, //注释结束
C_NO_MATCH, //注释不匹配
C_SUCCESS //注释转换成功
}STATE;
int flag = 0;//解决C++注释问题 当 flag == 1 时表示出现C++问题
STATE AnnotationCovert(FILE* fIn, FILE* fOut)
{
assert(fIn);
assert(fOut);
char first, second;
STATE sta= C_END;
do
{
first = fgetc(fIn);
switch (first)
{
case '/':// /*xxxxxxxxxxxx*/
{
second = fgetc(fIn);
if (second == '*'&& sta == C_END)//>>>>>解决一般问题
{
fputc('/',fOut);
fputc('/', fOut);
sta = C_BEGIN;
}
else if (second == '/')//解决C++注释问题
{
fputc('/', fOut);
fputc('/', fOut);
sta = C_BEGIN;
flag = 1;
}
else//>>>>>>>>解决匹配问题
{
fputc(first, fOut);
fputc(second, fOut);
}
break;
case '*':
{
second = fgetc(fIn);
if (second == '/' && sta == C_BEGIN && flag == 0)
{
fputc('\n',fOut);//>>>>>解决换行问题
sta = C_END;
}
else if (second == '/' && sta == C_BEGIN && flag == 1)//解决C++注释问题
{
fputc(first, fOut);
fputc(second, fOut);
sta = C_END;
flag = 0;
}
else
{
fputc(first, fOut);
fseek(fIn, -1, SEEK_CUR);//>>>>>>解决连续的**/问题
}
break;
}
case '\n': //>>>>>>>>>>>>>解决多行注释问题
{
fputc(first, fOut);
if (sta == C_BEGIN)
{
fputc('/', fOut);
fputc('/', fOut);
}
break;
}
default:
{
fputc(first, fOut);
break;
}
}
}
} while (first != EOF);
if (sta == C_END)
{
return C_SUCCESS;
}
else
{
return C_NO_MATCH;
}
}
void TestConvert()
{
FILE* fIn = fopen("input.c", "r");
if (fIn == NULL)
{
printf("file open fail. errno:%d\n", errno);
return;
}
FILE* fOut = fopen("output.c", "w");
if (fOut == NULL)
{
fclose(fIn);
printf("file open fail. errno:%d\n", errno);
return;
}
STATE ret = AnnotationCovert(fIn, fOut);
if (ret == C_SUCCESS)
{
cout << "注释转换成功!" << endl;
}
else if (ret == C_NO_MATCH)
{
cout << "注释转换失败!" << endl;
}
else
{
cout << "未知错误!请仔细核查!" << endl;
}
}
int main()
{
TestConvert();
system("pause");
return 0;
}
原注释:
转换后的注释: