I am trying to remove a line inside a text file using c++. for example, I have a .txt file that contains text:
booking.txt
1 jer 34 r er
2 43 45 34 456
3 2 4 5 6
4 45 546 435 34
5 cottage 1 323 23
6 we we r we
7 23 34 345 345
8 wer wer wer we
I want to remove a line when a certain condition is meet. let say I want to remove the 3rd line, the line with the id of 3 must be remove from the .txt file.
My Code:
void DeleteLine(string filename)
{
string deleteline;
string line;
ifstream fin;
fin.open(filename);
ofstream temp;
temp.open("temp.txt");
cout << "Input index to remove [0 based index]: "; //input line to remove
cin >> deleteline;
while (getline(fin, line))
{
line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;
}
temp.close();
fin.close();
remove("cottage.txt");
rename("temp.txt", "cottage.txt");
}
but gives me the following result:
1 jer 4 r er
2 4 45 34 456
2 4 5 6
4 45 546 45 34
5 cottage 1 23 23
Currently you delete only the first occurrence of deleteline
in each line. To delete the whole line starting with deleteline
you have to replace
line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;
with
std::string id(line.begin(), line.begin() + line.find(" "));
if (id != deleteline)
temp << line << endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.