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

时间:2013-08-03 08:46:23

标签: c++ file-io

我试图从输入文件打印,当时只有一组条目,但是当我尝试打印时,它会显示两次,我无法弄清楚原因。任何帮助,将不胜感激。继承人的代码

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

1 个答案:

答案 0 :(得分: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;