C++ 在文件中查找特定单词并删除其行

C++ 在文件中查找特定单词并删除其行,c++,file,overwrite,C++,File,Overwrite,正如标题所示,我试图在文件中找到一个特定的单词,然后删除包含它的行,但我在这里所做的操作会破坏文件的内容: cin>>ID; //id of the line we want to delete ifstream read; read.open("infos.txt"); ofstream write; write.open("infos.txt"); while (read >> name >> surname >> id) { if

正如标题所示,我试图在文件中找到一个特定的单词,然后删除包含它的行,但我在这里所做的操作会破坏文件的内容:

cin>>ID; //id of the line we want to delete
ifstream read;
read.open("infos.txt"); 
ofstream write; 
write.open("infos.txt");
while (read >> name >> surname >> id) {
    if (ID != id) {
        write << name << " " << surname << " " << id << endl; 
    }
    else write << " ";
    }
    read.close();
    write.close();

两个文件的名称相同。调用basic_of stream::open会破坏文件中已经存在的内容。在您的情况下,您在执行任何操作之前都会销毁输入文件中的数据。使用不同的名称,然后重命名。我假设输入中的行以\n结尾,因此我们可以使用getline。然后我们需要知道这个词是否出现在队列中,以及是否存在。std::string:npos在行中不包含单词时返回

#include <cstdio> // include for std::rename
#include <fstream>
#include <string>

void removeID() {
    std::string ID;
    cin >> ID; //id of the line we want to delete
    ifstream read("infos.txt");
    ofstream write("tmp.txt"); 
    if (read.is_open()) {
       std::string line;
       while (getline(read, line)) {
          if (line.find(ID) != std::string::npos)
             write << line;
       }
    } else {
       std::cerr << "Error: coudn't open file\n";
       /* additional handle */
    }

    read.close();
    write.close();
    std::remove("infos.txt");
    std::rename("tmp.txt", "infos.txt");
}

欢迎来到堆栈溢出。请提供更多的细节,而不是这不起作用-请参阅,因此没有任何方法可以从同一文件中删除?为什么需要它?你最终得到了与旧文件同名的更新文件。在看到编辑之前,我问:这个方法也很好,很高兴我能帮上忙。你应该把这个问题标记为已回答