c++:刪除文件註釋和將文件裏面的行註釋換成塊註釋

測試了幾種情況,不知道還有沒有沒有考慮到的情況

 

刪除文件註釋和將文件裏面的行註釋轉換成塊註釋

 

#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;
}


 


 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章