您的位置:首页 > 编程语言 > C语言/C++

C语言的注释与C++注释的转换

2015-12-18 11:04 465 查看
本博客主要考虑以下几种情况,可能有的地方没有考虑到,望读者指出。
// 1.一般情况
/* int i = 0; */

// 2.换行问题
/* int i = 0; */int j = 0;
/* 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*/

以下为主要代码:
主函数:
#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include "AnnotationConver.h"

int main()
{
AnnotationConver("input.c", "output.c");
system("pause");
return 0;
}
AnnotationConver.h:
#pragma once

typedef enum State
{
C_BEGIN,
C_END,
}State;

void AnnotationConver(const char *inputFile,
const char *outputFile);
AnnotationConver.c:
#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "AnnotationConver.h"

static void Convert(FILE *fIn, FILE *fOut)
{
assert(fIn);
assert(fOut);
char first = 0;
char second = 0;
State tag = C_END;
do
{
first = fgetc(fIn);
switch (first)
{
case '/':
second = fgetc(fIn);
if (second == '*')
{
if (tag == C_END)
{
fputc('/', fOut);
fputc('/', fOut);
tag = C_BEGIN;
}
else
{
fputc(first, fOut);
fputc(second, fOut);
}
}
else if (second == '/')
{
fputc('/', fOut);
fputc('/', fOut);
char next = fgetc(fIn);
while (next != '\n'&& next != EOF)
{
fputc(next, fOut);
next = fgetc(fIn);
}
if (next == '\n')
{
fputc(next, fOut);
}
}
else
{
fputc(first, fOut);
fputc(second, fOut);
}
break;
case '\n':
if (tag == C_BEGIN)
{
fputc(first, fOut);
fputc('/', fOut);
fputc('/', fOut);
}
else
{
fputc(first, fOut);
}
break;
case '*':
second = fgetc(fIn);
if (second == '/')
{
//换行问题
char next = fgetc(fIn);
/*连续注释*/
if (next == '/')
{
fseek(fIn, -1, SEEK_CUR);
}
/*换行问题*/
else
{
if (next != '\n'&& next != EOF)
{
fputc('\n', fOut);
}
if (next != EOF)
{
fputc(next, fOut);
}
}
tag = C_END;
}
/*连续的**问题*/
else if (second == '*')
{
fputc(second, fOut);
fseek(fIn, -1, SEEK_CUR);
}
else
{
fputc(first, fOut);
fputc(second, fOut);
}
break;
default:
if (first != EOF)
{
fputc(first, fOut);
}
break;
}
} while (first != EOF);
}

void AnnotationConver(const char *inputFile,
const char *outputFile)
{
assert(inputFile);
assert(outputFile);
FILE *fIn = fopen(inputFile,"r");
if (fIn == NULL)
{
printf("打开文件%s失败! errno: %d\n", inputFile, errno);
return;
}
FILE *fOut = fopen(outputFile, "w");
if (fOut == NULL)
{
fclose(fIn);
printf("打开文件%s失败! errno: %d\n", outputFile, errno);
return;
}
Convert(fIn, fOut);

fclose(fIn);
fclose(fOut);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C语言 C++ 注释转换