【问题标题】:Deleting lines from file with number从带有数字的文件中删除行
【发布时间】:2017-12-14 16:04:34
【问题描述】:

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

代码1:它只需要第一行从源文件到临时文件。(由int标识的roomno)

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

【问题讨论】:

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


【解决方案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";
  }
}

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

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

【讨论】:

  • 非常感谢,但我试过了,现在当我输入数字时它会删除每一行
猜你喜欢
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2021-07-24
相关资源
最近更新 更多