测试了几种情况,不知道还有没有没有考虑到的情况
删除文件注释和将文件里面的行注释转换成块注释
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void ClearNote(string & FileName);
void LineToBlock(string & FileName);
void main()
{
cout<<"==================LineToBlock==================="<<endl;
LineToBlock(string("data2.txt"));
cout<<"==================ClearNote==================="<<endl;
ClearNote(string("data.txt"));
}
void LineToBlock(string & FileName)
{
ifstream infile(FileName.c_str(),ios::in);
ofstream outfile;
string Text="";
string Line="";
int index = 0;
int pos;
if(! infile.is_open() )
{
cout<<"open file Error"<<endl;
return ;
}
while(getline(infile,Line))
{
Text.append(Line);
Text.append("\n");
}
cout<<Text;
index = 0 ;
while( Text[index] )
{
if( Text[index] == '"' )
{ index++;
while( Text[index] )
{
if(Text[index]=='"' && index > 0 && Text[index-1]!='\\')
break;
index++;
}
}
if( Text[index]=='/' && Text[index+1]=='/' )
{
pos=Text.find('\n',index);
Text[index+1]='*';
/*对只有“///”和“///_* *_/”的情况处理*/
if( !(Text[pos-1] =='/' && Text[pos-2] =='*' && pos > index+3))
{
Text.insert(pos,"*/");
}
index = pos;
}
index++;
}
cout<<"==================after ChangeNote==================="<<endl;
cout<<Text;
/**/ outfile.open(FileName.c_str(),ios::out | ios::trunc);
if(!outfile.is_open())
{
cout<<"open file Error"<<endl;
return ;
}
outfile<<Text;
}
void ClearNote(string & FileName)
{
ifstream infile(FileName.c_str(),ios::in);
ofstream outfile;
string Text="";
string Line="";
int Flag = 0;
int index = 0;
int pos1,pos2;
if(! infile.is_open() )
{
cout<<"open file Error"<<endl;
return ;
}
while(getline(infile,Line))
{
Text.append(Line);
Text.append("\n");
}
cout<<Text;
index = 0 ;
while( Text[index] )
{
if( Text[index] == '"')
{ index++;
while( Text[index] )
{
if(Text[index]=='"' && index > 0 && Text[index-1]!='\\')
break;
index++;
}
}
if( Text[index]=='/' && Text[index+1]=='*' )
{
pos1= index;
pos2=Text.find("*/",pos1);
Text.erase(pos1,pos2-pos1+2);
}
if( Text[index]=='/' && Text[index+1]=='/' )
{
pos1= index;
pos2=Text.find('\n',pos1);
Text.erase(pos1,pos2-pos1);
}
index++;
}
cout<<"==================after delete note==================="<<endl;
/**/ cout<<Text;
outfile.open(FileName.c_str(),ios::out | ios::trunc);
if(!outfile.is_open())
{
cout<<"open file Error"<<endl;
return ;
}
outfile<<Text;
}