/********************************************************************************************
readfloats.cpp
Jim Millard
for CO211/Fall 1999
Program that reads floating points from a file and displays the largest value, the smallest
value and the average of values in the series.
The input filename has been hardcoded
********************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const char filename[] = "numbers.txt"; //this can be later changed to allow user input
float current, largest, smallest;
long double sum = 0.; //for maximum accuracy
int count = 0;
//no prompts: just get the data and work on it!
ifstream input(filename);
if (!input) //check for a found file
{
cerr << endl
<< "The file is invalid or not found. Check for \"" << filename << '"'<< endl
<< "in the current working directory."
<< endl << endl;
return -1; // error condition
}
else
{
if (input >> current) // check for a valid first entry
{
//force-fit the first value as both smallest and largest; init the sum.
count = 1;
largest = current;
smallest = current;
sum = current;
//extract the rest of the set
while (input >> current)
{
count++; //we've got valid input, so increment the count
sum += current; //accumulate the sum
//compare to currently held values
if (current > largest)
largest = current;
else if (current < smallest)
smallest = current;
} //while
} //if
//compute the average and display results
if (count)
cout << "Results" << endl
<< "------------------------------" << endl
<< "Largest: " << largest << endl
<< "Smallest: " << smallest << endl
<< "Average: " << sum / count << endl;
else
cout << "No valid data were read from \"" << filename << '"' << endl;
return 0;
} //else
}