【发布时间】: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());
【问题讨论】:
-
Visual Studio 有一个非常好的调试器,你真的应该使用它。 ericlippert.com/2014/03/05/how-to-debug-small-programs
-
读取文件的首选方法:
while (readFile >> room.roomno >> room.price).
标签: c++ visual-studio c++11