一、具体要求:
input.c
五、使用环境举例
1:C风格的注释/* */注释转换为标准C++风格//注释
2:// 风格的注释保持原样
3:所有的转换需要符合语法规则
4:注释转换需要支持注释嵌套
二、转换要求:
注释的嵌套情形很多,这里只是举例,你需要遵照C/C++语言的注释规则来编写代码,我不会仅测试这里的例子。
三、注意事项:
1、除以下两种情况的修改,源文件转换后不能有任何其它的修改:
a.多余的注释符用空格代替
b./* */在注释开始替换为// ,行尾去掉*/
2、注意下面的情形的转换
a. /******/
b.// /*……*/
3、不需要考虑输入文件中不符合语法规则的注释
四、代码:
main.c
#include <stdio.h>
#include <errno.h>
#include <assert.h>
typedef enum STATE
{
SUCCESS, // 成功
FILE_ERROE, // 文件错误
NO_MATCH, // 不匹配
OTHER, // 其他错误
}STATE;
typedef enum TAG
{
TAG_BEGIN, // 在C注释段中
TAG_END, // C注释结束
}TAG;
#pragma warning(disable:4996)
STATE AnnotationConvert(FILE* inFile, FILE* outFile)
{
TAG tag = TAG_END;
char firstCh, secondCh;
assert(inFile);
assert(outFile);
do{
firstCh = fgetc(inFile);
switch (firstCh){
// 1.一般情况
case '/':
secondCh = fgetc(inFile);
if (secondCh == '*'
&& tag == TAG_END)
{
fputc('/', outFile);
fputc('/', outFile);
// 3.匹配问题
tag = TAG_BEGIN;
}
else if(secondCh == '/')
{
char next;
fputc(firstCh, outFile);
fputc(secondCh, outFile);
// 7.C++注释问题
do
{
next = fgetc(inFile);
fputc(next, outFile);
} while (next != '\n'
&& next != EOF);
// 当读到文件尾时,标记firstCh
if(next == EOF)
{
firstCh = EOF;
}
}
else{
fputc(firstCh, outFile);
fputc(secondCh, outFile);
}
break;
case '\n':
fputc('\n',outFile);
// 4.多行注释问题
if (tag == TAG_BEGIN)
{
fputc('/',outFile);
fputc('/',outFile);
}
break;
case '*':
secondCh = fgetc(inFile);
if (secondCh == '/')
{
// 2.换行问题
// 5.连续注释问题
char next = fgetc(inFile);
if (next != '\n' && next != EOF)
{
fseek(inFile, -1, SEEK_CUR);
}
fputc('\n', outFile);
tag = TAG_END;
}
else if(secondCh == '*')
{
// 6.连续的**/问题
fseek(inFile, -1, SEEK_CUR);
fputc(firstCh, outFile);
}
else
{
fputc(firstCh, outFile);
fputc(secondCh, outFile);
}
break;
default:
fputc(firstCh, outFile);
break;
}
}while(firstCh != EOF);
if(tag == TAG_END)
{
return SUCCESS;
}
else
{
return NO_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)
{
return FILE_ERROE;
}
if (outFile == NULL)
{
fclose(inFile);
return FILE_ERROE;
}
s = AnnotationConvert(inFile, outFile);
fclose(inFile);
fclose(outFile);
return s;
}
int main()
{
STATE ret = StartConvert();
if (ret == SUCCESS)
{
printf("转换成功\n");
}
else if (ret == NO_MATCH)
{
printf("不匹配\n");
}
else if (ret == FILE_ERROE)
{
printf("文件错误: %d\n", errno);
}
else
{
printf("其他错误: %d\n", errno);
}
return 0;
}
input.c
// 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*/
五、使用环境举例
当遇到在Windows 下用VC2005环境写程序的时候, 有C++语言写的程序, 但是用了C的注释, 也能成功编译连接运行. 但发现也有很多编译器不支持C的单行注释. 又不想手动地改所有的代码. 将会用到如此一个程序来自动将C的注释替换成C++语言的注释格式.