从带有数字的文件中删除行

时间:2017-12-14 16:04:34

标签: c++ visual-studio c++11

我的c ++项目有问题。我按房间号码和价格列出房间,我想删除一个房间,我输入它的号码。 这是我的代码如下;我尝试了很多代码,但没有任何效果。当我想删除1号房间时,我的第一个删除功能是删除以1开头的每一行。 所以我改变了它,但现在代码只将文件的第一行放到另一个文件中。

代码1:它只从第一行获取来自源的临时文件。(roomno由int标识)

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());

1 个答案:

答案 0 :(得分:1)

您的程序可以简化:

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写入新文件。