我寫了一個函數,它使用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)
}
的[如何閱讀與同時文件可能的複製循環工作在C++?](https://stackoverflow.com/questions/14009737/how-does-reading-file-with-while-loops-work-in-c) – jww