尝试从输入文件打印,但打印最后一个输入两次
Trying to print from an input file but printing the last input twice
我试图从一个输入文件打印,当时该文件只有一组条目,但当我尝试打印时,它会显示两次,我不知道为什么。如有任何帮助,我们将不胜感激。这是代码
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;
相关文章:
- 打印时有二叉树问题.用户输入不打印任何内容
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 我要求用户输入大小和数组,但是当我打印矢量时,它仅显示'0'作为输出
- 如何打印不带空格的输入整数?
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 使用用户输入打印 6X10 矩阵的代码 - C++
- 如何使用打印到 PDF 打印机在 MFC 和 CView 中以编程方式打印而不提示输入文件名?
- 如何打印输入值
- 带有用户输入的C 文本数组,然后打印输入
- 读取和打印输入和 C 字符串C++
- 如何打印输入而不将其存储在c++中
- SFML—创建游标并打印输入
- c++的新功能,scanf不能正确读取/打印输入
- 如何打印输入的第一个数字?
- 如何自动打印输入的c++函数参数值
- C++:为什么 getline() 不打印输入字符串的最后一个单词?
- 打印输入的最小数字(不包括任何负数)
- 创建一个控制台应用程序,打开TCP/IP连接并用C++、C#或Java打印输入的字符串
- 从文件打印输入数据
- 按倒序打印输入字符串