首页 > 解决方案 > 如何使用 C++ 删除 .txt 中的记录

问题描述

如何删除 .txt 文件中的记录,例如我在 .txt 文件中有记录:

Juan John Josh
Harry Potter Harry
Razor Paper Stone

用户将输入他要删除的姓名,例如:用户输入姓名,Harry 然后记录将更新并删除记录 Harry Potter Harry。

我要一个代码。请回复。

标签: c++

解决方案


#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;
    }

推荐阅读