注释转换

 

将文件中的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;
}

 

 

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值