0

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

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();
}
4

1 回答 1

3

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;
于 2013-08-03T08:56:11.393 回答