Deleting lines from a given text file
I want to delete strings from the specified positions. For this, I have
written a function remove which is as follows:-
void remove()
{
int count_of_lines=1,to_be_deleted;
string
text,first_name("c:\\computer_programs\\cpp_programs\\"),last_name,filename;
cin.clear();
cin.sync();
cout<<"Enter the name of the source file:"<<endl;
getline(cin,last_name);
vector<string> v;
filename = first_name+last_name+".txt";
ifstream source_File(filename.c_str(),ios::in);
if(!source_File)
{
cout<<"File doesn't exist."<<endl;
exit(1);
}
display(filename);
cout<<"Enter the line that is to be deleted:"<<endl;
cin>>to_be_deleted;
getline(source_File,text);
while(!source_File.eof())
{
if(count_of_lines!=to_be_deleted)
v.push_back(text);
count_of_lines++;
getline(source_File,text);
}
source_File.close();
ofstream destFile(filename.c_str(),ios::out);
for(int i =0;i<v.size();i++)
destFile<<v[i]<<endl;
destFile.close();
}
This function should be deleting only the required strings ( given by
to_be_deleted ) but are deleting all the contents of the file. The logic
seems to be correct but I am unable to pinpoint the error because no error
is being shown, only the output is wrong. Can you please help?
No comments:
Post a Comment