2012-11-22 52 views
2

當我使用C++來處理文件時,我發現文件末尾總是有空行。有人說vim會在最後附加'\ n'的文件,但是當我使用gedit時,它也有同樣的問題。任何人都可以告訴我原因?C++處理文件空行在文件末尾

1 #include<iostream> 
2 #include<fstream> 
3 
4 using namespace std; 
5 const int K = 10; 
6 int main(){ 
7   string arr[K]; 
8   ifstream infile("test1"); 
9   int L = 0; 
10   while(!infile.eof()){ 
11    getline(infile, arr[(L++)%K]); 
12   } 
13   //line 
14   int start,count; 
15   if (L < K){ 
16    start = 0; 
17    count = L; 
18   } 
19   else{ 
20    start = L % K; 
21    count = K; 
22   } 
23   cout << count << endl; 
24   for (int i = 0; i < count; ++i) 
25    cout << arr[(start + i) % K] << endl; 
26   infile.close(); 
27   return 1; 
28 } 

while test1 file just: 
abcd 
but the program out is : 
2 
abcd 

(upside is a blank line) 

回答

3
while(!infile.eof()) 

infile.eof()僅是真的你試圖讀取超出文件的末尾。所以循環嘗試讀取多於一行的行,並在該嘗試中獲得空行。