一.将所有注释风格全部转换成c++风格
想法:既然要转换风格,第一步搞清楚注释有几种方式:
第一种无注释,第二种c注释,第三种c++注释。
可以把这三种方式看成一种状态-status
第二步:c注释分几种情况:末尾结束,注释中又有c注释或者c++注释
c++注释同样考虑清楚。
先写测试文件:
/*int w =2;*/ int j = 0; int i =9; //eioshr; /*ejre***/ //最好先考虑清楚再动手写,不然会修改很多次 int s = 3; /*int n =9; re =9; int e =3;*/ int a = 0;
再写头文件:
#ifndef _comment_convert_h_//条件编译,防止头文件被重复引用
#define _comment_convert_h_
#include
#include
#include
enum state
{//用枚举来标识状态,优点:防止命名污染,便于调试,维护,可以定义多个变量
nul_state, // 缺点:只能是整型常量,不能是浮点型
c_state,
cpp_state,
end_state
};
void donulstate(file *pfin,file *pfout,enum state *ps);
void docstatestate(file *pfin,file *pfout,enum state *ps);
void docppstate(file *pfin,file *pfout,enum state *ps);
void commentconver(file *pfin,file *pfout);
#endif //_comment_convert_h_ //结束,最好注释一下
再写运行文件:
#include"commentcovert.h"
int main()
{
file *pfin = null;
file *pfout = null;
pfin =fopen("input.c","r");//打开一个文件,用r来读
if(pfin == null)
{
perror("error opening file"); //perror 错误信息返回
exit(exit_failure);//退出
}
pfout = fopen("pfout.c","w"); //写
if(pfout == null)
{
fclose(pfin);
pfin = null;
perror("eorror opening file");
exit(exit_failure);
}
commentconver(pfin,pfout);
fclose(pfin);
pfin = null;
fclose(pfout);
pfout = null;
return 0;
}
接着写函数接口文件:
#include"commentcovert.h"
void commentconver(file *pfin,file *pfout)
{
enum state status = nul_state; //默认状态值是无注释
while(status != end_state)
{
switch(status)
{
case nul_state:
donulstate(pfin,pfout,&status);
break;
case c_state:
docstatestate(pfin,pfout,&status); //c注释
break;
case cpp_state:
docppstate(pfin,pfout,&status);//c++注释
break;
}
}
}
void donulstate(file *pfin,file *pfout,enum state *ps)
{
int first = fgetc(pfin);
switch(first)
{
case '/':
{
int second = fgetc(pfin);
switch(second)
{
case '/':
{
fputc('/',pfout);
fputc('/',pfout);
*ps = cpp_state;
}
break;
case '*':
{
fputc('/',pfout);
fputc('/',pfout);
*ps = c_state;
}
break;
case eof:
*ps = end_state;
break;
default:
{
fputc(first,pfout);
fputc(second,pfout);
}
break;
}
}
break;
case eof:
*ps = end_state;
break;
default:
{
fputc(first,pfout);
break;
}
}
}
void docstatestate(file *pfin,file *pfout,enum state *ps)
{
int first = fgetc(pfin);
switch(first)
{
case '*':
{
int second= fgetc(pfin);
switch(second)
{
case '/':
{
int third = fgetc(pfin);
fputc('\n',pfout);
*ps = nul_state;
}
break;
default :
{
int four = 0;
ungetc(second,pfin);//把读出的那个字符返回去
fputc(first,pfout);
}
break;
}
}
break;
case '\n':
{
;
}
break;
default:
fputc(first,pfout);
break;
}
}
void docppstate(file *pfin,file *pfout,enum state *ps)
{
int first = fgetc(pfin);
switch(first)
{
case '\n':
{
fputc(first,pfout);
*ps = nul_state;
}
break;
case eof:
*ps = end_state;
default:
fputc(first,pfout);
break;
}
}
最后看结果是不是转换成功
//int w =2; int j = 0; int i =9; //eioshr; //ejre** int s = 3; //int n =9;re =9;int e =3; int a = 0;
羊羊疯