c++ - 如何使用 C++ 删除 .txt 中的记录
问题描述
如何删除 .txt 文件中的记录,例如我在 .txt 文件中有记录:
Juan John Josh
Harry Potter Harry
Razor Paper Stone
用户将输入他要删除的姓名,例如:用户输入姓名,Harry 然后记录将更新并删除记录 Harry Potter Harry。
我要一个代码。请回复。
解决方案
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char** arg)
{
//declare testing this is the original text file variable
ifstream testing;
//open test.txt this is the original text file
testing.open("test.txt");
//decalare a temporary text file variable
ofstream temp;
//open a temporary text file
temp.open("temp.txt");
// user input to delete record
cout<<"Enter Name to delete: ";
//declaration of variables
//variable for the input of the user
string name;
//variable for the record inside the original text file
string name1;
//reading input as the value of the variable name.
cin>>name;
//while this is for reading the original text file and the record will be the value for the variable name1
while(testing>>name1)
{
//if variable name2(record) not equal to variable name(input)
if(name2 != name)
{
//all the records in the original text file except to the record that the user inputted will be copied to the temporary text file which is temp.txt.
temp<<name1<<" "<<name2<<" "<<name3<<" "<<grade1<<" "<<grade2<<" "<<grade3<<endl;
}
}
//closing temp.txt
testing.close();
//closing original text file which is test.txt
temp.close();
//removing the original text file because it contains all the records including the record that was intended to be deleted.
remove("test.txt");
//renaming the temporary text file(temp.txt) to become the original text file(test.txt)
//note: that the temporary text file contains all the records except to the record the user deleted.
//and now renamed to be the original text file.
rename("temp.txt", "test.txt");
//the record is now deleted and its done hahaha
return 0;
}
推荐阅读
- autodesk-forge - 通过 forge 查看器访问的模型的应用程序级别访问管理
- python - openstack Python sdk:执行启动脚本的用户数据
- r - R - 用列中的最大值替换序列值
- c - 让 GStreamer 应用程序接收像流视频或 rtsp 流一样的 FPS?
- html - 为什么angualr生成的最终DOM中有额外的注释标签
- r - ggplot:日期轴。如何设置限制?
- rust - 如何在每个结构上自动#derive(Something)(可能带有过滤)?
- python - 如何为每次迭代从 scipy.optimize.least_squares 获取梯度?
- reactjs - 如何在反应材料ui CardMedia组件中包含图像
- regex - 扩展正则表达式