gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:33:16 25 4
gpt4 key购买 nike

我的教授告诉我们创建一个能够添加、列出和删除员工记录的程序,我的问题是我不知道如何从文件中删除记录。我使用的代码只是复制原始文件的内容,而不是新内容。

这是我的代码:

string del;
string line;
ifstream in("sample.txt");
if (!in.is_open()) {
cout << "Input file failed to open\n";
}
ofstream out("temp.txt")`enter code here`;
cout << "Please Enter the Employee No. to delete" << endl;
cin >> del;
while (getline(in, line)) {
if (line != del)
out << line << endl;
}
in.close();
out.close();
remove("sample.txt");
rename("temp.txt", "sample.txt");

最佳答案

i dont know how i can delete a record from the file . the code that i'm using is its only copying the content of the original file and not the new content.

您不能从文本文件中删除特定行。您只能将相同的内容重写到要删除的行到另一个文件中,跳过要删除的行,继续写入其余内容。

完成后,删除原始文件并将新文件重命名为原始文件。

您的代码在做同样的事情,没问题。

另一种方法是将当前文件内容存储在数据结构中,例如 Vector。在数据结构中进行删除/添加等更改。

然后将数据结构的内容写回文件。

关于c++ - 如何删除文件中的特定行 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com