删除包含搜索词的行的问题

Problem with deleting a line, that consists the searched word

Data.txt 文件:

John Smith Freshman U2010001
Kirti Seth Freshman U2010002
Nick Johnson Freshman U2010003
Alan Walker Freshman U2010004
Peter Foster Freshman U2010005

一旦用户输入 his/her ID,程序会找到行号,其中已输入的 ID 存在,并且新文件 NEWFILE.txt 应存储所有行,除了行,但出于某种原因,我的代码只是存储该行下方的行,其中存在用户 ID,而不是存储所有行并跳过该行。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string Delete_this_Line;
string line, Aline;
int LineNumber = 1, i=1;

ifstream Read("Data.txt", ios::in);
ofstream NewFile("NewFile.txt", ios::out | ios::app);

if (Read.is_open())
{
    cout << "ID (to be deleted): ";
    cin >> Delete_this_Line;
    while (!Read.eof()) 
    {
        getline(Read, line);
        size_t found = line.find(Delete_this_Line);
        if (found != string::npos)
        {               
            break;
        }
        LineNumber++;
    }
    while (!Read.eof()) // for each candidate word read from the file 
    {
        i++;
        getline(Read, Aline);
        NewFile << Aline << "\n";
        if (i == LineNumber)
        {
            continue;
        }
    }
}
Read.close();
NewFile.close();
return 0;
}

当我输入 ID U2010003 时,编译器将以下数据复制到 NEWFILE.txt 文件中:

NEWFILE.txt:

Alan Walker Freshman U2010004
Peter Foster Freshman U2010005

但我希望得到以下结果 => NEWFILE.txt:

John Smith Freshman U2010001
Kirti Seth Freshman U2010002
Alan Walker Freshman U2010004
Peter Foster Freshman U2010005

老实说,我不知道为什么会这样,你能帮我达到预期的结果吗?

你是misusing the ifstream::eof() method。更重要的是,您正在使用 2 个单独的循环,1 个循环查找要删除的 ID,1 个循环复制该 ID 之后的所有行,忽略 ID 之前的所有行。对所有内容使用 1 个循环就足够了,例如:

#include <iostream>
#include <stream>
#include <string>

using namespace std;

int main()
{
    string Delete_this_Line, line;

    ifstream Read("Data.txt");
    if (Read.is_open())
    {
        ofstream NewFile("NewFile.txt");
        if (NewFile.is_open())
        {
            cout << "ID (to be deleted): ";
            cin >> Delete_this_Line;

            while (getline(Read, line)) 
            {
                if (line.find(Delete_this_Line) == string::npos)
                    NewFile << line << "\n";
            }
        }
    }
    return 0;
}