2009-10-22 20 views
0

我可以從文件中讀取字符串,但是在刪除或清空該字符串時遇到問題。 感謝您的幫助和美好的一天。如何清空文件中的一行並將其寫回原始位置?

#include <iostream> 
#include <fstream> 
#include <map> 
#include <string> 
#include <cstdlib> 
#include <sstream> 

using namespace std; 

int main() { 
    map<string, string> Data; // map of words and their frequencies 
    string key;    // input buffer for words. 
    fstream File; 
    string description; 
    string query; 
    int count=0; 
    int i=0; 

    File.open("J://Customers.txt"); 

    while (!File.eof()) { 
     getline(File,key,'\t'); 
     getline(File,description,'\n'); 
     Data[key] = description; 
    } 

    File.close(); 

    cout << endl; 

    for (count=0; count < 3; count++) { 
     cout << "Type in your search query."; 
     cin >> query; 
     string token[11]; 
     istringstream iss(Data[query]); 
     while (getline(iss, token[i], '\t')) { 
      token[0] = query; 
      cout << token[i] << endl; 
      i++;   
     } 
    } 
    system("pause"); 

}//end main 
+0

你能告訴我們到底什麼** **你想達到什麼目的? – Jacob 2009-10-22 01:21:16

+0

我想從文本文件 中刪除數據[查詢]對不起,因爲不清楚在第一位 – Tim 2009-10-22 01:26:34

回答

1

基本上,底層文件系統本身不支持。
所以你需要手動完成。

  • 打開要在讀模式下修改文件。
  • 以寫入模式打開臨時文件。
  • 將讀取的文件複製到寫入文件中。
    • 請勿複製要刪除的行。
  • 關閉這兩個文件
  • 交換文件系統
  • 文件刪除舊文件。

看你的代碼:
你不應該這樣做:

while (!File.eof()) 
{ 
    getline(File,key,'\t'); 
    getline(File,description,'\n'); 
    Data[key] = description; 
} 

文件將不設置EOF正確因此你將再次進入循環,但兩個函數getline中的最後一行()調用將失敗。

幾個選項:

while (!File.eof()) 
{ 
    getline(File,key,'\t'); 
    getline(File,description,'\n'); 
    if(File) // Test to make sure both getline() calls worked 
    { Data[key] = description; 
    } 
} 

// or more commonly put the gets in the condition 

while (std::getline(File,line)) 
{ 
    key   = line.substr(0,line.find('\t')); 
    description = line.substr(line.find('\t')+1); 
    Data[key] = description; 
} 
相關問題