【问题标题】:Trying to print from an input file but printing the last input twice尝试从输入文件打印但将最后一个输入打印两次
【发布时间】:2013-08-03 08:46:22
【问题描述】:

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

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

【问题讨论】:

标签: c++ file-io


【解决方案1】:

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;

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2022-06-12
    相关资源
    最近更新 更多