2017-05-13 136 views
1

我寫了一個函數,它使用while循環從輸入文件中讀取事務。我不能爲了我的生活找出它爲什麼要讀兩次最後兩行。當使用C++ while循環從輸入文件中讀取

while(InFile){code} 

從我的理解,它將繼續循環,直到文件達到EOF標記。我無法弄清楚我在這裏出錯的地方。

void ProcessTransactions(Bank &acctList, string fileName) 
{ 

    Date transDate; 
    ifstream InFile; 
    InFile.open(fileName.c_str()); 
    int month; 
    int day; 
    int year; 
    int acctNum; 
    int transAcctNum; 
    float amount; 
    string transType; 

    while(InFile) 
    { 
     InFile >> month >> day >> year; 
     transDate.SetDate(month, day, year); 

     InFile >> acctNum; 
     InFile >> amount; 
     InFile >> transType; 
     if(transType == "Transfer") 
      InFile >> transAcctNum; 

     cout << amount << endl; 
    } 
} 

輸入文件

5 1 2012 1212 100.00 Deposit 
5 1 2012 2323 100.00 Deposit 
5 1 2012 3434 100.00 Deposit 
6 1 2012 1212 200.00 Withdrawal 
6 1 2012 2323 200.00 Withdrawal 
6 1 2012 3434 50.00 Withdrawal 
7 1 2012 1212 50.00 Transfer 
2323 
7 1 2012 2323 80.00 Transfer 
3434 
7 1 2012 3434 300.00 Transfer 
1212 
9 1 2012 1212 100.00 Deposit 
9 1 2012 2323 100.00 Deposit 
9 1 2012 3434 100.00 Deposit 
10 1 2012 1212 300.00 Transfer 
1212 

輸出

100 
100 
100 
200 
200 
50 
50 
80 
300 
100 
100 
100 
300 
300 //** Why is this output twice ? 

它提取數據的最後一位後,文件標記應該已經達到EOF,從而終止循環。

任何幫助將不勝感激!

============================================== =========================== 附加說明/解決方案:從 : Why is iostream::eof inside a loop condition considered wrong?

因爲的iostream :: EOF只會返回閱讀完流後,爲true。它並不表示,下一次讀取將是流的結束。

考慮這個(並假設,然後下一個讀將在流的末尾)

while(!inStream.eof()){ 
    int data; 
    // yay, not end of stream yet, now read ... 
    inStream >> data; 
    // oh crap, now we read the end and *only* now the eof bit will be 
    set (as well as the fail bit) 
    // do stuff with (now uninitialized) data 
} 

在此:

int data; 
while(inStream >> data){ 
    // when we land here, we can be sure that the read was successful. 
    // if it wasn't, the returned stream from operator>> would be 
    // converted to false 
    // and the loop wouldn't even be entered 
    // do stuff with correctly initialized data (hopefully) 
} 
+0

的[如何閱讀與同時文件可能的複製循環工作在C++?](https://stackoverflow.com/questions/14009737/how-does-reading-file-with-while-loops-work-in-c) – jww

回答

5

它提取數據的最後一位後,文件標記應該已經到達EOF,終止循環。當你嘗試讀取過去文件的末尾

EOF設置。在這裏,你不檢查你的提取是否成功,只有在你嘗試提取之前流是可以的。因此,你會在最後得到一個額外的迭代。

你應該循環這樣的(並有大量的堆棧溢出這樣的例子,因爲我們在不斷地告訴人們如何做到這一點):

while (InFile >> month >> day >> year) 
+0

謝謝你的解釋!與while(!InFile.eof)相比,這樣做的好處是什麼。只是它在同一時間檢查/提取? – jslice

+0

@jslice閱讀http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –

+0

@jslice:這個答案的第二段解釋了爲什麼。 –