可以分为7种情况
1.一般情况
/* int i = 0; */
2.换行问题
/* 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;
3.匹配问题
//int i = 0;/*xxxxx
4.多行注释问题
//
//int i=0;
//int j = 0;
//int k = 0;
//
int k = 0;
5.连续注释问题
//
//
6.连续的**/问题
//*
7.C++注释问题
// /xxxxxxxxxxxx/
#include<stdio.h>
#include<assert.h>
#include<errno.h>
#pragma warning (disable:4996)
typedef enum STATE
{
SUCCEED, //转换成功
FILE_ERROR, //文件错误
NOT_MATCH, //注释不匹配
OTHERS, //其他错误
}STATE;
typedef enum TAG
{
TAG_BEDIN,//在c注释段内
TAG_END, //注释结束
}TAG;
STATE AnnotationConvert(FILE* InFile, FILE* OutFile)
{
TAG tag = TAG_END;
char firstch;
char secondch;
assert(InFile);
assert(OutFile);
do
{ firstch = fgetc(InFile);
switch(firstch)
{
case(‘/‘):
secondch = fgetc(InFile);
if (secondch == ‘*‘&& tag == TAG_END)
{
fputc(‘/‘, OutFile);
fputc(‘/‘, OutFile);
tag = TAG_BEDIN;
}
else
{
fputc(firstch, OutFile);
fputc(secondch, OutFile);
if (secondch == ‘/‘)
{
char nextch;
do
{ nextch = fgetc(InFile);
fputc(nextch, OutFile);
} while (nextch != ‘\n‘ && nextch != EOF);
}
}
break;
case(‘\n‘) :
fputc(firstch, OutFile);
if (tag == TAG_BEDIN)
{
fputc(‘/‘, OutFile);
fputc(‘/‘, OutFile);
}
break;
case(‘*‘) :
secondch = fgetc(InFile);
if (secondch == ‘/‘)
{
char nextch = fgetc(InFile);
tag = TAG_END;
fputc(‘\n‘, OutFile);
if (nextch == ‘/‘)
{
fseek(InFile, -1, SEEK_CUR);
}
else if (nextch != ‘\n‘)
{
fputc(nextch, OutFile);
}
}
else
{
fputc(firstch, OutFile);
fseek(InFile, -1, SEEK_CUR);
}
break;
default:
fputc(firstch, OutFile);
break;
}
} while (firstch != EOF);
if (tag == TAG_END)
{
return SUCCEED;
}
else
return NOT_MATCH;
}
int startconvert()
{
STATE s;
const char* infilename = "input.c";
const char* outfilename = "output.c";
FILE* InFile = fopen(infilename, "r");
FILE* OutFile = fopen(outfilename, "w");
if (InFile == NULL)
{
perror("input.c");
return FILE_ERROR;
}
if (OutFile == NULL)
{
fclose(InFile);
perror("output.c");
return FILE_ERROR;
}
s = AnnotationConvert(InFile, OutFile);
fclose(InFile);
fclose(OutFile);
return s;
}
int main()
{
STATE ret = startconvert();
if (ret == SUCCEED)
{
printf("转换成功\n");
}
else if (ret == NOT_MATCH)
{
printf("注释不匹配\n");
}
else if (ret == FILE_ERROR)
{
printf("文件错误:%d\n", errno);
}
else
{
printf("其他错误\n");
}
getchar();
return 0;
}
时间: 2024-10-12 20:00:46