How do I determine the min and max numbers from a list of numbers in a txt file?This is what I have that isn't working. I've figured out how to preform the other functions I need this program to do but thought someone might be able to assist me with this.
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream inFile;
double
sum = 0, // Sum of the numbers in the file
average = 0, // Average of the numbers in the file
min = average, // The smallest number in the file
max = average; // The largest number in the file
int number,
count = 0; // How many numbers have been read from file
// Open the file.
inFile.open("C:\\Users\\Kunze\\Documents\\Visual Studio 2015\\Projects\\file_Tester\\Random.txt");
cout << "Reading data from the file.\n";
// If the file successfully opened, process it.
if (inFile)
{
// Read the numbers from the file and
// display them.
while (inFile >> number)
{
count++;
sum += number;
if
(number < min)
cout << "The lowest number in the file is: " << min << endl;
max = number;
if
(number > max)
cout << "The highest number in the file is: " << max << endl << endl;
}
// Calculate how many numbers were read from file.
cout << "Total number of Numbers in file: " << count << endl;
// Calculate the sum of the numbers in the file (running Total)
cout << "The sum of the numbers in the file are: " << sum << endl;
// The average of the number in the file ( sum / total)
average = sum / count;
cout << "The average number in the file is: " << average << endl;
// Determine the lowest and highest values in the file
while (inFile >> number)
// Close the file.
inFile.close();
}
else
{
// Display an error message.
cout << "Error opening the file.\n";
}
return 0;
}
To achieve this you need to loop through the entire data comparing the numbers to the lowest value that has been found which you've partly achieved already. The problem is that you're outputting the 'lowest' and 'highest' value of the file when you've not even read the whole file yet! What you need to do is move the part where you output the lowest and highest outside of the while (inFile >> number) { ... } loop. And inside the loop you keep the current if (number < min) { ... } and if (number > max) { ... } statements but when they resolve to true you update the min or max variable respectively.
EDIT: Didn't notice this before but line 53 needs to be removed otherwise you're getting further input from the file and by then the whole file has been read, and if it was valid it would close the file every cycle. Just a note for anyone looking at this thread in the future.