这应该是一个非常简单的程序。我的问题是最后一个数字重复了,我完全理解这一点,因为在回到循环并读取数字之前,EOF没有被达到,那时已经太晚了。我可以通过做类似于“如果(!fileIn)break;count ++”这样的事情来解决这个问题,在for循环中放置“fileIn >> num”(如果(count > 1),我会进入计算平均值、输出总数、平均值等的最后一个代码块)。唯一的问题是我的教授不想在这个程序中使用break,所以我只是想看看如何解决它。
谢谢。
输入文件:
346 130 982 90 656 117 595
415 948 126 4 558 571 87
42 360 412 721 463 47 119
441 190 985 214 509 2 571
77 81 681 651 995 93 74
310 9 995 561 92 14 288
466 664 892 8 766 34 639
151 64 98 813 67 834 369
#include <iostream>
#include <fstream>
using namespace std;
const int NumPerLine = 7;
int main()
{
int num = 0;
int total = 0;
float average = 0;
int min = 0;
int max = 0;
ifstream fileIn;
fileIn.open("File2.txt");
ofstream fileOut("Output.txt");
if (!fileIn) {
cout << "/nError opening file...Closing program. n";
exit(1);
}
while (fileIn) {
cout << endl;
int total = 0;
int count = 0;
for (int k = 0; k < NumPerLine; k++) {
fileIn >> num;
if (k == 0) {
max = num;
min = num;
}
total += num;
cout << num << " ";
fileOut << num << " ";
if (num > max)
max = num;
if (num < min)
min = num;
}
average = total / NumPerLine;
cout << "/n/nTotal is " << total << "." << endl;
cout << "Average is " << average << "." << endl;
cout << "Lowest number is " << min << endl;
cout << "Largest number is " << max << endl;
fileOut << "/n/nTotal is " << total << "." << endl;
fileOut << "Average is " << average << "." << endl;
fileOut << "Lowest number is " << min << endl;
fileOut << "Largest number is " << max << endl << endl;
}
fileIn.close();
fileOut.close();
cout << "/nData has been processed, and copied to the file, " Output.txt "." << endl << endl;
return 0;
}