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++語言的註釋格式.