close

我們在讀檔時 , 因為不知道檔案的大小 , 通常需要一個方法來幫我們判斷是否已經讀到檔案結尾.

but ... You should never use feof() as the exit indicator for a loop. 

feof() is TRUE only after the end of file (EOF) is read, not when EOF is reached. 

To test this, create a normal text file (mine is feof.fil):

for example , if the content of test file is 

this is a test file.

#include <fstream> 
using namespace std; 
int main () 
ifstream ifs ( "test.txt" , ifstream::in ); 
string str;
while (!ifs.eof()
{
ifs >> str;
cout << str << endl; 
}
ifs.close(); 
return 0; 
}
the output will be
this
is
a
test
file.
file.
因為feof的pointer是判斷目前指向的地方 , 而不是我們所要到達的地方.
所以在讀到"file."時 , 在進到loop判斷仍然會被判斷為true.
所以最好的方法是 , 我們可以直接使用ifs >> str來進行判斷是否已經讀到EOF
 
#include <fstream> 
 
using namespace std; 
 
int main () 
 
 
ifstream ifs ( "test.txt" , ifstream::in ); 
 
string str;
 
while (ifs >> str
 
{
 
cout << str << endl; 
 
}
 
ifs.close(); 
 
return 0; 
 
}

ref : http://www.gidnetwork.com/b-58.html

arrow
arrow
    全站熱搜

    JerryCheng 發表在 痞客邦 留言(0) 人氣()