如果我在一個文件中有一個客戶記錄如果我有兩個客戶名稱john doe但是他們有不同的電話號碼,我該如何刪除該文件中的客戶記錄。基本上我想知道如何使用姓名和電話號碼從文件中刪除客戶記錄。這是我的代碼。從文件中刪除
void deleteCustomerData() {
string name, customerInfo, customerData;
string email;
string phoneNumber;
string address;
string deleteCustomer;
int skip = 0;
cout << "Enter the name of the Customer record you want to delete: " << endl;
getline(cin, name);
cout << "Enter the phone number of the Customer record you want to delete: " << endl;
getline(cin, customerData);
ifstream customerFile;
ofstream tempFile;
int tracker = 0;
customerFile.open("customer.txt");
tempFile.open("tempCustomer.txt");
while (getline(customerFile, customerInfo)) {
if ((customerInfo != name) && !(skip > 0)) {
if ((customerInfo != "{" && customerInfo != "}")) {
if (tracker == 0) {
tempFile << "{" << endl << "{" << endl;
}
tempFile << customerInfo << endl;
tracker++;
if (tracker == 4)
{
tempFile << "}" << endl << "}" << endl;
tracker = 0;
}
}
}
else
{
if (skip == 0)
skip = 3;
else
--skip;
}
}
cout << "The record with the name " << name << " has been deleted " << endl;
customerFile.close();
tempFile.close();
remove("customer.txt");
rename("tempCustomer.txt", "customer.txt");
}
'std :: string'都是可變長度的。所以你不能事先合理地分配必要的內存。我更喜歡一個解決方案,將所有行讀入一個'std :: vector'找到要刪除的行,將其從該向量中刪除並將其寫回文件。 –
它工作正常,直到我必須刪除兩個同名客戶 – kadrian