These are the contents of my example file:
abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA FIND ME akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH
I need to find and delete the 'FIND ME' inside of the file so the output would look like this:
abcdefg hijk lmnopqrstAB CSTAKLJSKDJD KSA akjsdkjhwjkjhasfkajbsdh ADHKJAHSKDJH
I have tried the following method of doing getline and then writing all of the contents except the FIND ME into a temporary file and then rename the temporary file back.
string deleteline;
string line;
ifstream fin;
fin.open("example.txt");
ofstream temp;
temp.open("temp.txt");
cout << "Which line do you want to remove? ";
cin >> deleteline;
while (getline(fin,line))
{
if (line != deleteline)
{
temp << line << endl;
}
}
temp.close();
fin.close();
remove("example.txt");
rename("temp.txt","example.txt");
but it doesn't work.
Just as a side note: the file has NO newline/linefeeds. So the file contents are all written in 1 line.
EDIT:
FIXED CODE:
while (getline(fin,line))
{
line.replace(line.find(deleteline),deleteline.length(),"");
temp << line << endl;
}
This gets me the results I expected. Thank you everyone for helping!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…