C++ while循环从输入文件中读取

jsl*_*ice 1 c++ loops while-loop

我编写了一个函数,使用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  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
Run Code Online (Sandbox Code Playgroud)

输出

100
100
100
200
200
50
50
80
300
100
100
100
300
300 //** Why is this output twice ?
Run Code Online (Sandbox Code Playgroud)

在提取最后一位数据后,文件标记应该已达到EOF,从而终止循环.

任何帮助将非常感激!

================================================== =======================附加说明/解决方案:from: 为什么循环条件中的iostream :: eof被认为是错误的?

因为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
 }
Run Code Online (Sandbox Code Playgroud)

反对这个:

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)
}
Run Code Online (Sandbox Code Playgroud)

Lig*_*ica 6

在提取最后一位数据之后,文件标记应该已达到EOF,终止循环.

没有.

当你试图读取EOF设定过去的文件的末尾.在这里,您不会检查您的提取是否成功,只是您尝试提取之前,流是可以的.因此,您最终会获得额外的迭代.

你应该像这样循环(在Stack Overflow上有很多例子,因为我们经常告诉人们如何去做):

while (InFile >> month >> day >> year)
Run Code Online (Sandbox Code Playgroud)