【问题标题】:C++ while loop to read from input fileC++ while循环从输入文件中读取
【发布时间】:2017-10-12 20:37:20
【问题描述】:

我编写了一个函数,它使用 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++ loops while-loop


【解决方案1】:

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

没有。

EOF 在您尝试读取过去文件末尾时设置。在这里,您不会检查您的提取是否成功,而只是在您尝试提取之前检查流是否正常。因此,您将在最后获得额外的迭代。

你应该像这样循环(在 Stack Overflow 上有很多这样的例子,因为我们一直在告诉人们怎么做):

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

【讨论】:

  • 感谢您的解释!与 while(!InFile.eof) 相比,这样做有什么好处。只是同时检查/提取?
  • @jslice:这个答案的第二段解释了原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 2022-01-21
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多