最近幫老師帶C++的課程設計,很多同學在使用很多fstream流的eof()函數進行
while(!readfile.eof())
{
readfile>>x;
}
時,會出現將最后一行數據讀兩次。
eof是end of file的意思,用來判斷是否到了文件結尾。微軟的文檔說明如下:
bool eof( ) const;
Return Value
true if the end of the stream has been reached, false otherwise.
Remarks
The member function returns true if rdstate & eofbit is nonzero. For more information on eofbit,
see ios_base::iostate.
按照一般思維,應該就是到達文件尾,就eof()應返回true,但事實上,在讀完最后一個數據時,eofbit仍然是false。只有當流再往下讀取時,發現文件已經到結尾了,才會將標志eofbit修改為true。這也就是為什么使用while(!readfile.eof())會出多現讀一行的原因。
既然已經知道了原因,那么,為了避免這樣的情況,可以使用readfile.peek()!=EOF來判斷是否到達文件結尾,這樣就能避免多讀一行。更改為:
while(readfile.peek()!=EOF)
{
readfile>>x;
}
但是應注意,文件中最后一個數據之后,不應有多余的空白行。