注释转换(C->C++)

C语言的注释是/*  */     而C++的注释是//

转换思路:

1.设置两个状态,分别为注释中、注释外

2..逐次读取input.txt中的字符

a) 遇到 ‘/’ 读取下一个字符即判断是C还是C++注释的开始,若为‘*’同时在注释外,向output.txt输出两个‘/’字符即转换为C++注释;若遇到‘/‘表示为C++注释打印改行至output.txt

b)若为’*’,读取下一个字符,若为‘/’,查看下一个字符不为‘\n’,回退字符,输出换行,再读取输入;

c)若为‘/n’,若在注释中,输出‘/n’并向文件输出两个’/‘


INPUT.txt

// 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*/  
annotation.h
#pragma once 
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdlib.h>
#define IN "INPUT.txt"
#define OUT "OUTPUT.txt"
#pragma warning (disable:4996)

enum FLAG
{
	IN_ANN,
	OUT_ANN
};

void ConvertWork(FILE* pfin,FILE* pfout);
annotationConvert.cpp
#include "annotation.h"

void ConvertWork(FILE* pfin, FILE* pfout)
{
	enum FLAG flag = OUT_ANN;
	char first = fgetc(pfin);
	while (first != EOF)
	{
		char second;
		switch (first)
		{
		case '/':
			second = fgetc(pfin);
			if (second == '/')  //C++注释 打完一行
			{
				fputc(first, pfout);
				fputc(second, pfout);
				char third;
				while ((third = fgetc(pfin)) != '\n')
				{
					fputc(third, pfout);
				}
				fputc('\n', pfout);
			}
			else if (second == '*' && flag == OUT_ANN)  //C语言注释 开始
			{
				flag = IN_ANN;
				fputc('/', pfout);
				fputc('/', pfout);
			}			
			else
			{
				fputc(first, pfout);
				fputc(second, pfout);
			}
			break;
		case '*':
			second = fgetc(pfin);
			if (second == '/'  && flag == IN_ANN)  
			{//对1来说文件尾就什么都不做
				flag = OUT_ANN;
				char third = fgetc(pfin);    //  针对*/结尾又有字符7
				if (!isspace(third))
				{
					fputc('\n', pfout);
					ungetc(third,pfin);
				}
			}
			else if (second == '*')
			{
				fputc(first, pfout);
				ungetc(second, pfin);
			}
			break;
		case '\n':       //  4          
			fputc('\n', pfout);
			if (flag == IN_ANN)
			{
				fputc('/', pfout);
				fputc('/', pfout);
			}
			break;  
		default:
			fputc(first,pfout);
			break;
		}
		first = fgetc(pfin);
	}
}
main.cpp
#include "annotation.h"



int main()
{
	FILE *pfin = fopen("INPUT.txt", "r");
	if (NULL == pfin)
	{
		printf("Open sourse file failed");
		exit(EXIT_FAILURE);
	}
	FILE *pfout = fopen("OUTPUT.txt", "w");
	if (NULL == pfout)
	{
		fclose(pfin);
		printf("Open dest file failed");
		exit(EXIT_FAILURE);
	}
	ConvertWork(pfin, pfout);
	fclose(pfin);
	fclose(pfout);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值