After a bit of thinking I got a better idea.
Code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <exception>
#include <cstdio>
const int NUMBER_COUNT = 7;
using namespace std;
class Record
{
public:
int min_value() const
{
check_valid();
return *min_element(numbers.begin(), numbers.end());
}
int max_value() const
{
check_valid();
return *max_element(numbers.begin(), numbers.end());
}
int sum() const
{
check_valid();
return accumulate(numbers.begin(), numbers.end(), 0);
}
double avg() const
{
return double(sum()) / numbers.size();
}
private:
void check_valid() const
{
if(numbers.size() != NUMBER_COUNT)
throw exception("numbers.size() != NUMBER_COUNT");
}
vector<int> numbers;
friend ostream& operator<<(ostream& os, const Record& rec);
friend istream& operator>>(istream& os, Record& rec);
};
int main()
{
ifstream infile("numbers.txt");
if (!infile)
{
cerr << strerror(errno) << "\n\n";
exit(1);
}
ofstream outfile("numbers_out.txt");
if (!outfile)
{
cerr << strerror(errno) << "\n\n";
exit(1);
}
try
{
for(Record rec; infile >> rec;)
{
cout << rec << "\n";
// to do - save to file
}
}
catch (const exception& ex)
{
cerr << ex.what() << "\n\n";
return errno;
}
}
ostream & operator<<(ostream & os, const Record & rec)
{
os << "Min: " << rec.min_value() << "\tMax: " << rec.max_value() <<
"\tSum: " << rec.sum() << "\tAvg: " << rec.avg();
return os;
}
istream & operator >> (istream & is, Record & rec)
{
string line;
stringstream ss;
int num = 0;
rec.numbers.clear();
getline(is, line);
ss << line;
while (ss >> num)
{
rec.numbers.push_back(num);
}
return is;
}
Output:
Min: 90 Max: 982 Sum: 2916 Avg: 416.571
Min: 12 Max: 948 Sum: 2655 Avg: 379.286
Min: 42 Max: 721 Sum: 2164 Avg: 309.143
Min: 2 Max: 985 Sum: 2912 Avg: 416
Min: 74 Max: 995 Sum: 2652 Avg: 378.857
Min: 9 Max: 995 Sum: 2269 Avg: 324.143
Min: 8 Max: 892 Sum: 3469 Avg: 495.571
Min: 64 Max: 834 Sum: 2396 Avg: 342.286