用数字删除文件

Deleting lines from file with number

本文关键字:文件 删除 数字      更新时间:2023-10-16

我的C 项目有问题。我有房间数量和价格列出的房间,我想删除一个我输入数字的房间。这是下面我的代码;我尝试了很多代码,但没有任何效果。我的第一个删除函数是删除以1开始的每一行,当我想删除房间1时。所以我更改了它,但是现在代码只将文件的第一行获取到另一个文件。

代码1:仅将第一行从源到临时文件。

void deleteRoom() {
    rooms room;
    string source;
    string line;
    source = "Room.txt";
    {
        ifstream readFile;
        readFile.open("Room.txt");
        system("cls");
        cout << "Room Number" << setw(13) << "Price" << "n---------------------------------------------n";
        while (true) {
            readFile >> room.roomno >> room.price;
            if (readFile.eof()) { break; }
            cout << setw(6) << room.roomno << setw(16) << room.price << " $" << endl;
        }
        readFile.close();
        cout << "---------------------------------------------n" << "Enter the room number that you want to remove : ";
        cin >> room.roomno;
        ifstream s(source);
        ofstream t("temp.txt");
        while (getline(s, line)) {
            int len;
            if (room.roomno > 0) {
                for (len = 0; room.roomno > 0; len++) {
                    room.roomno = room.roomno / 10;
                    int n = len;
                    int abc = atoi(line.c_str());
                    if (abc != room.roomno)
                        t << satir << endl;
                }
            }
        }
        t.close();
        s.close();
        remove(source.c_str());
        rename("temp.txt", source.c_str());
    }
}

代码2:当我输入要删除的房间号时,它将删除每行以此数字开头。例如:当我输入1时,它删除每个房间以1开头。)

roomno由字符串确定。

ifstream s(source); //string line and string source before that
ofstream t("temp.txt");
while (getline(s, line))
{
    int n;
    if (room.roomno.size() == 1)  n = room.roomno.size();
    else if (room.roomno.size() == 2)  n = room.roomno.size() + 1;
    else if (room.roomno.size() == 3)  n = room.roomno.size() + 2;
    else if (room.roomno.size() == 4) n = room.roomno.size() + 3;
    string abc = line.substr(0, n);
    if (abc != room.roomno)
        t << line << endl;
}
t.close();
s.close();
remove(source.c_str());
rename("temp.txt", source.c_str());

您的程序可以简化:

rooms  room;
int room_to_delete = 0;
cout << "Enter room to be deleted: ";
cin >> room_to_delete;
while (readfile >> room.roomno >> room.price)
{
  if (room.roomno != room_to_delete)
  {
    t << room.roomno << room_to_delete << "n";
  }
}

在上面的片段中,从源文件中读取一个房间。如果房间不是要删除的房间,则将其复制到输出文件t

还有其他方法,例如将整个文件读取到std::vector中,修改std::vector,然后将std::vector写入新文件。