我刚刚在这个答案中发现了一条评论说iostream::eof在循环条件下使用"几乎肯定是错误的".我通常使用类似的东西while(cin>>n)- 我猜是隐式检查EOF,为什么检查eof显式使用while (!cin.eof())错误?
它与scanf("...",...)!=EOF在C中使用有何不同(我经常使用没有问题)?
我编写了一个函数,使用while循环从输入文件中读取事务.我不能为我的生活弄清楚为什么它会读两遍最后两行.使用时
while(InFile){code}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,它将继续循环,直到文件到达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;
}
}
Run Code Online (Sandbox Code Playgroud)
输入文件
5 1 2012 1212 100.00 Deposit
5 1 2012 2323 100.00 Deposit
5 1 2012 3434 100.00 …Run Code Online (Sandbox Code Playgroud)