用数字删除文件
Deleting lines from file with number
我的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
写入新文件。
相关文章:
- 如何在我从C++文件中读取后立即删除行
- 删除 XML 文件中的子节点C++
- 如何在输入新内容 c++ 之前删除文件中的所有内容
- 如何更新和删除文本文件中的特定逗号分隔值?C++
- 为什么我的程序在读取/写入文件时会删除最重要的数字?
- 将内容从第一个文件("constituencies")移动到第二个文件("temp")并在之后重命名时,我的文件被删除
- 文件模式标志"ios::app"是否用于删除文件(如果文件已存在)?
- 如何自动获取我的项目的路径并删除一些文件
- C++ VS 错误:<实验/文件系统>提供 std::experimental::文件系统的标头已被Microsoft弃用,将被删除
- 如果我删除指针,我的C++程序会意外删除系统文件吗?
- 在 c++ 中打开文件、删除标点符号并追加到另一个文件中
- 文件删除(使用取消链接)与释放所有磁盘空间之间的延迟
- 重命名批处理文件(删除名称中的一些符号)(python/matlab/shell)
- 如何找到字符串并使用C 文件中的文件删除它
- 使用 DEF 文件删除 dll 导出的名称
- 关闭后等待文件删除
- c++中的文件删除
- 如何共享文件删除权限时,我打开一个文件ifstream
- 典型的Win32文件删除(IDropTarget::drop)实现
- 生成文件模式规则:循环生成文件.o < - 删除生成文件依赖项