C语言实现C到C++的注释转换

    C语言中的注释一般为/*......*/来标注,C++的注释一般为//来标注,为了完成注释的转换,我考虑了一下几种情:

    1.一般情况

    /* int i = 0; */

    这是最通常的情况,当遇到/*时把其替换成//,遇到*/时直接跳过

    2.换行问题

    /* int i = 0; */int j = 0;

    /* int i = 0; */

    int j = 0;

    如果存在换行,或者C语言中的注释没有换行,我们就要考虑,若注释后面有换行符,直接打印,若无,则加上换行符,再打印后面的内容

    3.匹配问题

    /*int i = 0;/*xxxxx*/

    若注释内容存在/*,我们必须打印出来,为此,我定义了一个枚举变量State,用来判断内容是否存在注释内,便可以很好的解决

    4.多行注释问题

    /*

    int i=0;

    int j = 0;

    int k = 0;

    */int k = 0;

    如若内容存在注释内且有换行,那么一个//是不够把它都注释掉的,所以在内容内的换行之前,可以加上//

    5.连续注释问题

    /**//**/

    解决完以上问题,因为我已经连续读取了3个字符,所以遇到连续注释的情况,只能转换第一个注释,并不能转换第二个注释,所以用fseek函数,将读取内容退回文件,防止出现纰漏。

    6.连续的**/问题

    /***/

    这个问题与上一条类似,只是把第二个读取的字符退回就好了。

    7.C++注释问题

    // /*xxxxxxxxxxxx*/

    如果这让,则单独判断是否注释前有C++注释,若有,则换行在转换C的注释,这样做比直接取消掉C的注释要好很多,如果//写有内容 /*xxxxxxxxxxxx*/,也可以让层次分得清楚。

    代码如下:

#include <stdio.h>
#include <errno.h>
#include <assert.h>
typedef enum Con_State
{
Con_SUCCESS,
Con_FAIL
}Con_State;
typedef enum State
{
C_BEGIN,
C_END
}State;
Con_State Convert(FILE*fout, FILE*fin)
{
int flag = C_END;//匹配问题
char first=0;
char second=0;
char next = 0;
assert(fout);
assert(fin);
while ((first = fgetc(fout)) != EOF)
{
switch (first)
{
case '/':
second = fgetc(fout);
if ((second == '*')&&flag==C_END)
{
flag = C_BEGIN;
fputc('/', fin);
fputc('/', fin);
}
else if (second == '/')//C++注释问题
{
fputc(first, fin);
fputc(second, fin);
fputc('\n', fin);
}
else
{
fputc(first, fin);
fputc(second, fin);
}
break;
case '\n'://多行注释问题
if (flag == C_BEGIN)
{
fputc(first, fin);
fputc('/', fin);
fputc('/', fin);
}
else
{
fputc(first, fin);
}
break;
case '*':
second = fgetc(fout);
if ((second == '/')&&(flag==C_BEGIN))
{
flag = C_END;
if (((next = fgetc(fout)) != '\n')&&(next!=EOF))//换行问题,连续注释问题
{
fputc('\n', fin);
}
fseek(fout, -1, SEEK_CUR);//连续的** / 问题
}
else
{
fputc(first, fin);
fseek(fout, -1, SEEK_CUR);//连续的** / 问题
}
break;
default:
fputc(first, fin);
break;
}
}
return Con_SUCCESS;
}
Con_State annotaCon()
{
FILE* fout;
FILE* fin;
int ret = 0;
fout = fopen("output.c", "r");
if (fout == NULL)
{
printf("打开%s失败error:%d\n", "output", errno);
return Con_FAIL;
}
fin = fopen("input.c", "w");
if (fin == NULL)
{
printf("打开%s失败error:%d\n", "input", errno);
fclose(fout);
return Con_FAIL;
}
ret=Convert(fout, fin);
fclose(fout);
fclose(fin);
return ret;
}

 

    如有什么不足之处,希望批评指正。

本文出自 “pawnsir的IT之路” 博客,请务必保留此出处http://10743407.blog.51cto.com/10733407/1725650

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值