2016-03-04 138 views
-3

如果我在一個文件中有一個客戶記錄如果我有兩個客戶名稱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"); 
} 

回答

0

假設一個客戶記錄在您的文件中的行,你需要:

  1. 分配內存的讀取文件。
  2. 將文件讀入內存。
  3. 修改內存。
  4. 用修改的內容覆蓋文件。
  5. 釋放您分配的內存。
+0

'std :: string'都是可變長度的。所以你不能事先合理地分配必要的內存。我更喜歡一個解決方案,將所有行讀入一個'std :: vector '找到要刪除的行,將其從該向量中刪除並將其寫回文件。 –

+0

它工作正常,直到我必須刪除兩個同名客戶 – kadrian

0

我不知道OP的文件格式,所以我不得不泛泛而談。

定義客戶結構

struct customer 
{ 
    string name; 
    string email; 
    string phoneNumber; 
    string address; 
}; 

寫入功能在客戶讀取或返回是否可以不假。也許,如果你有一個看起來像函數重載>>操作最簡單:

std::istream & operator>>(std::istream & in, customer & incust) 

Write函數寫出來的客戶或返回是否可以不假。同樣,如果你超載<<運營商最簡單。

std::ostream & operator<<(std::ostream & out, const customer & outcust) 

使用流操作符允許您利用流的布爾運算符來判斷讀取或寫入是否成功。

然後使用讀寫功能,實現以下幾點:

while read in a complete customer from input file 
    if customer.name != deletename or customer.phoneNumber!= deletenumber 
     Write customer to output file 

英文:只要我可以從輸入讀取文件中的客戶,我會寫的客戶,如果他們對輸出文件不是我想要刪除的客戶。

隨着過載流運營商,這可能是一樣簡單

customer cust; 
while (infile >> cust) 
{ 
    if (cust.name != deletename || cust.phoneNumber != deletenumber) 
    { 
     outfile << cust; 
    } 
} 

所有的「大腦」是在讀取和寫入功能和選擇邏輯是死的簡單。客戶匹配並且不寫入文件或不匹配並寫入文件。

所有的讀寫邏輯都與選擇邏輯分開,可以輕鬆地重複使用多種不同類型的搜索。

但是,您可能會發現緩存中的某些優點,只需讀入一次即可構建std::vectorcustomers以便在不必連續讀取和重寫文件的情況下進行操作。

+0

我是新的我不明白上面的任何東西。 – kadrian

+0

大的收穫是1.將客戶存儲在一個結構中。處理好的,明確定義的包中的數據要容易得多。 2.製作讀取功能和寫入功能,一次只能讀取或寫入一個客戶。您可以獨立測試和完善讀取和寫入功能,而無需擔心其他代碼中的錯誤會妨礙您的工作。然後,您可以根據讀取和寫入功能編寫程序的其餘部分,而不必擔心讀取和寫入中的錯誤。這會導致3.將應用程序邏輯與實用程序邏輯分開。 – user4581301