删除包含单词的行

Delete a line that contain a word

本文关键字:包含单 删除      更新时间:2023-10-16

我正在尝试删除包含文本文件中特定单词的行但这不起作用

void deleteline()
{
    string line, deletecontact;
    cout << "Plase enter the contact (name or number) to delete:";
    cin >> deletecontact;
    ifstream file;
    ofstream outfile;
    file.open("data.txt");
    outfile.open("newM.txt");
    while (getline(file, line)) {
        if (line != deletecontact) {
            outfile << line << endl;
        }
    }
    outfile.close();
    file.close();
    remove("movieList.txt");
    rename("newM.txt", "data.txt");
}

预先感谢您

您仅在线相等时删除线路(即 line != deleteContact)。如果您想删除仅包含此词的行,则应写出以下内容:

if (strstr(line.c_str(), deleteContact.c_str()) == nullptr) ...