将文件中的c风格的注释转换为c++风格的注释,并保存在另一个文件中
思路:(有限自动机)
图解:一般情况
#include<stdio.h>
#pragma warning(disable:4996)
typedef enum condition{//状态定义
NOT_ANNOTATION,//不是注释
MAYBE_IN_ANNOTATION,//可能进入注释
C_ANNOTATION,//C风格注释
CPP_ANNOTATION,//C++风格注释
MAYBE_OUT_ANNOTATION//可能出注释
}Condition;
int main()
{
FILE *pIn = fopen("input.c", "rt");
if (pIn == NULL){
perror("fopen test");
return 1;
}
FILE *pOut = fopen("output.c", "wt");
if (pOut == NULL){
fclose(pIn);
perror("fopen out");
return 1;
}
char ch;
Condition state = NOT_ANNOTATION;
do{
ch = fgetc(pIn);
switch (state)
{
case NOT_ANNOTATION:
{
if (ch == '/'){
state = MAYBE_IN_ANNOTATION;
fputc(ch, pOut);
}
else{
state = NOT_ANNOTATION;
fputc(ch, pOut);
}
break;
}
case MAYBE_IN_ANNOTATION:
{
if (ch == '/'){
state = CPP_ANNOTATION;
fputc(ch, pOut);
}
else if (ch == '*'){
state = C_ANNOTATION;
fputc('/', pOut);
}
else{
state = NOT_ANNOTATION;
fputc(ch, pOut);
}
break;
}
case CPP_ANNOTATION:
{
if (ch == '\n'){
state = NOT_ANNOTATION;
fputc(ch, pOut);
}
else{
fputc(ch, pOut);
}
break;
}
case C_ANNOTATION:
{
if (ch == '*'){
state = MAYBE_OUT_ANNOTATION;
}
else{
fputc(ch, pOut);
if (ch == '\n'){
fprintf(pOut, "//");
}
}
break;
}
case MAYBE_OUT_ANNOTATION:
{
if (ch == '*'){
state = MAYBE_OUT_ANNOTATION;
fputc(ch, pOut);
}
else if (ch == '/'){
char nextch = fgetc(pIn);//向前看一个字符
if (nextch != '\n'){
fputc('\n', pOut);//做出判断
}
ungetc(nextch, pIn);//将看的字符放回所读的缓冲区中
state = NOT_ANNOTATION;
}
else{
state = C_ANNOTATION;
fputc('*', pOut);
fputc(ch, pOut);
}
break;
}
}
} while (ch != EOF);
fclose(pOut);
fclose(pIn);
return 0;
}
运行结果: