2

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
jreloz
  • 413
  • 4
  • 18
  • 3
    The program is doing exactly what you told it to. If you wanted to remove the entire line, why are you writing it to the output? – Sneftel Dec 12 '19 at 06:53
  • This code is prompting the user for a **line index** but is then searching for the user's input as a **substring** of each line instead. That makes no sense. Fix the prompt to ask for what the code really wants. – Remy Lebeau May 28 '22 at 18:39

1 Answers1

4

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;
Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62