尝试从输入文件打印,但打印最后一个输入两次

Trying to print from an input file but printing the last input twice

本文关键字:打印 输入 两次 最后一个 文件      更新时间:2023-10-16

我试图从一个输入文件打印,当时该文件只有一组条目,但当我尝试打印时,它会显示两次,我不知道为什么。如有任何帮助,我们将不胜感激。这是代码

ifstream orders;    
int idNum = 0;
int quantity = 0;
double totalCost = 0;
orders.open("processedOrders.dat");
if (orders.is_open())
{
cout << "Order Number" << setw(16) << "Quantity" << setw(22) << "Total Cost" << endl;
    while (!orders.eof())
    {
        orders >> idNum >> quantity >> totalCost;
        cout << "  " << idNum << setw(18) << quantity << setw(23) << totalCost << endl;
    }
        orders.close();
}

EOF标记尚未读取,这将调用下一次迭代,因此最后一行将读取两次。

检查循环内的EOF,如下所示:-

if (orders.is_open())
{
cout << "Order Number" << setw(16) << "Quantity" << setw(22) << "Total Cost" << endl;
    while (true)
    {
        orders >> idNum >> quantity >> totalCost;
        if( orders.eof() ) break;
        cout << "  " << idNum << setw(18) << quantity << setw(23) << totalCost << endl;
    }
        orders.close();
}

以下内容也应达到预期结果:

if (orders.is_open())
 while (orders >> idNum >> quantity >> totalCost) 
   cout << "  " << idNum << setw(18) << quantity << setw(23) << totalCost << endl;