C++如何删除文本文件中的特定行

How to delete a specific line in a text file in c++

我正在尝试使用 C++ 删除文本文件中的一行。例如,我有一个包含文本的 .txt 文件:

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

我想在满足特定条件时删除一行。假设我想删除第 3 行,id 为 3 的行必须从 .txt 文件中删除。

我的代码:

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");
}

但给了我以下结果:

1 jer 4 r er
2 4 45 34 456
 2 4 5 6
4 45 546 45 34
5 cottage 1 23 23

目前您只删除每行中第一次出现的 deleteline。要删除以 deleteline 开头的整行,您必须替换

line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;

std::string id(line.begin(), line.begin() + line.find(" "));
if (id != deleteline)
    temp << line << endl;