c++中ifstream讀文件的問題(關於eof())


  今天幫別人找BUG,是一段關於c++讀寫文件的問題,使用的是ifstream與outstream類,關於ofstream與ifstream的用法,此處不再獒述,見代碼:

#include<iostream>
#include<fstream>
using namespace std;

 int main()
 {
     ofstream outfile("student.dat");
     char name[8],id[8];
     int math,eng,computer;

     for(int  i = 0; i < 3; ++i)
     {

         cout<<" input name:  "; cin>>name;
         cout<<" input id:  "; cin>>id;
         cout<<" input math:  "; cin>>math;
         cout<<" input eng:  ";cin>>eng;
         cout<<" input computer:  "; cin>>computer;
        //寫文件
         outfile<<name<<" "<<id<<" "<<math<<" "<<eng<<" "<<computer<<endl;
         
     }

   向文件寫完之后,再從文件中讀取,源碼如下:
include<iostream>
#include<fstream>
using namespace std;

 int main()
 {
     ifstream infile("student.dat");
     char name[8],id[8];
     int math,eng,computer;
    
     int i = 0;
     char c;
     while((c=infile.get())!=EOF)
       {
         
         infile>>name>>id>>math>>eng>>computer;
         cout<<"name:  "<<name<<endl;
         cout<<"id:  "<<id<<endl;
         cout<<"math:  "<<math<<endl;
         cout<<"eng:  "<<eng<<endl;
         cout<<"computer:  "<<computer<<endl;


     }
     infile.close();

 }
 
         

 

  

看似無問題,但每次從文件中讀出的結果總會多出一組數據(最后一組數據會讀出兩邊),找了好久都沒有發現,經網上查閱資料總結為以下幾點:

   1.由於采用的寫入語句為“outfile<<name<<" "<<id<<" "<<math<<" "<<eng<<" "<<computer<<endl;“,即每次寫完一組數據后,都會向文件中寫入一個回車符,所以在讀文件的時候,當讀到最后一組數據時,讀完之后,文件中還有一個回車符沒有讀出來,此時判斷eof()並不為-1,故還會再進行一次讀操作;這次讀操作實際上並沒讀到什么,但還有一個輸出,輸出的為上次讀操作的結果,故最后一組數據顯示兩次。

 2.eof()判斷的是文件中所有的字符包括回車,只有當文件中什么字符都沒有了,才會返回-1,到達文件的末尾。

 3.故再使用infile和outfile對文件進行操作時,應該先讀再判斷(例如,本例中,先讀一個name,再進行判斷,當遇到最后一個回車符時,會有infile>>name這個操作正好解決了它這樣能保證你寫的和讀的內容是一樣的。

4.所以,較好的讀文件方式如下

infile>>name;
while((c=infile.get())!=EOF)
       {
         
         infile>>id>>math>>eng>>computer;
         cout<<"name:  "<<name<<endl;
         cout<<"id:  "<<id<<endl;
         cout<<"math:  "<<math<<endl;
         cout<<"eng:  "<<eng<<endl;
         cout<<"computer:  "<<computer<<endl;

        infile>>name;
   

     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM