Reputation: 641
This is supposed to be a very simple program. My issue is that the last number repeats itself, and I fully understand this because EOF is not reached until I get back inside the loop and read the number, which, at that time, is too late. I can get around this by doing something like, "If (!fileIn) break; count++" after I put "fileIn >> num" in the for loop(and if (count > 1), I would get into the last block of code that calculates average, outputs total, average, etc.). Only problem is that my professor doesn't want breaks in this program, so I'm just trying to see how else to solve it.
Thanks.
INPUT FILE:
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;
}
Upvotes: 3
Views: 154
Reputation: 153840
Always check the state of the stream after you attempted to read it: if the input failed the stream is nut into failure mode (i.e. std::ios_base::failbit
is set) and the stream converts to false
.
Upvotes: 1
Reputation: 2578
Instead of working with a while loop, you may use a do/while
(specially because of initial non NULL check):
do {
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;
} while(fileIn);
Upvotes: 1