2014-11-05 79 views
-4

該程序的工作原理是在開始時打印垃圾值(ch = 2)並打印兩次相同的輸出。 我使用這個爲我的project.It包含更多的數據,在那裏我用一個單一的對象,而不是數組對象。它沒有工作。 數組的每個對象都存儲一組數據。在讀取和寫入文件時出錯

#include<iostream> 
    #include<fstream> 
     using namespace std; 
     class rw    //a class containing some data 
     { 
      public: 
      int n; 
      char a; 
      }; 
     int main() 

     { 
      int i; 
      rw r[2];   //an array of objects 
      int ch; 
      fstream f1; 
      f1.open("file1.txt",ios::in|ios::out|ios::ate); 
      cout<<"1-read,2-write"; 
      cin>>ch; 
      f1.seekp(0,ios::beg); 
      if(ch==1)//for saving 
      { 
        r[0].n=1; 
        r[0].a='a'; 
        f1.write((char*) &r[0],sizeof(r[0])); 
        r[1].n=2; 
        r[1].a='b'; 
        f1.write((char*)&r[1],sizeof(r[1])); 
        } 
      if(ch==2)//for reading 
      { 
        f1.seekg(0,ios::beg); 
      while(!f1.eof()) 
      { 
          i=0; 
          cout<<r[i].n<<r[i].a; 
          cout<<"\n"; 
          f1.read((char*)&r[i],sizeof(r[i])); 
          i++; 
          } 
          } 
          system("pause"); 
          return 0; 
          } 
+0

你是什麼意思'沒有工作',請你能詳細說明一下嗎?程序崩潰了嗎?它只是不寫出文件? – cybermonkey 2014-11-05 09:01:33

回答

0

更改下面的代碼

cout<<r[i].n<<r[i].a; 
cout<<"\n"; 
f1.read((char*)&r[i],sizeof(r[i])); 

f1.read((char*)&r[i],sizeof(r[i])); // Moved before printing 
cout<<r[i].n<<r[i].a; 
cout<<"\n"; 

你輸出的數據然後從文件讀取,而不是你應該閱讀,然後再打印。在閱讀之前打印是在第一輪循環中獲取垃圾的原因。我想你移動了下面的讀數,以避免最後一個記錄的雙重打印。繼續閱讀以瞭解如何避免雙重閱讀。

您應該避免使用while (!f1.eof()),因爲它會將最後的數據打印兩次。 更好地利用while(f1.read((char*)&r[i],sizeof(r[i])));

展開循環的EOF版本2個輸入

while(!eof) // true 
read first data 
print first data 
while(!eof) // true 
read second data // read all, but was succesful and eof not set 
print second data 
while(!eof) // true 
Try to read // Could not read, eof set 
print data // Reprinting second data 
while(!eof) // false 
+0

你已經在'while'中讀取了,所以你不應該在循環中再讀一遍。 – 2014-11-05 09:11:07

+0

我刪除它..現在崩潰 – 2014-11-05 09:12:33

+0

循環如何終止? – 2014-11-05 09:13:03

0

不要使用while (!f1.eof()),你指望它,因爲eofbit標誌沒有設置直到將無法​​正常工作在之後,您嘗試從文件之外讀取。相反,例如while (f1.read(...))

還要小心這樣的循環沒有邊界檢查。如果文件不正確,您可能會寫出超出數組範圍r

+0

這應該是一個評論,因爲它不回答問題(請參閱上面的@ Mohit的回答)。 – cybermonkey 2014-11-05 09:02:34

+0

@cybermonkey這不是一個*完整的答案,因爲它回答了兩個OP的問題,因爲Mohits回答處理了另一個案例,但不是這個(在我寫這個答案的時候)。 – 2014-11-05 09:15:09

+0

這仍然不是答案,就我所知,OP僅詢問了一個問題(實際上沒有提出任何問題!)。 – cybermonkey 2014-11-05 09:17:01