C++ - How to loop through files?

I have a program below that calculates the average, sum, etc of the numbers in a file named "mynumberlist1.txt".

I want to create a loop whereby the program loops through several files; mynumberlist2.txt, mynumberlist3.txt, and calculates the statistics for all relevant files using the calculations below. How would I do this?

#include <iostream>
#include <cmath>
#include <math.h>
#include <fstream>
#include <string>
#include <numeric>
using namespace std;

int main()
{
ifstream infile;
float num;
float total;
float x;
float aver;

x = 0; total = 0;
infile.open("mynumberlist1.txt");

while (!infile.eof())
{
infile >> num;
total = total + num;
x++;
}

aver = (total - num) / (x - 1);

cout << "The last number in this range is: " << num << "\n";
cout << "The sum of this range is: " << (total - num) << '\n';
cout << "The number of items in this range is: " << x - 1 << '\n';
cout << "The average of this range is: " << aver << '\n';
cout << "" << '\n';
cout << "Press any key to continue..." << '\n';

infile.close();

getchar();
return 0;
}
for example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void statistics(std::string filename)
{
    std::ifstream infile(filename); 
    double total = 0;
    double x = 0; 
    double num;
    while (infile >> num)
    {
        total = total + num;
        ++x;
    }
    double aver = total / x;
    std::cout << "statistics for file " << filename << '\n';
    std::cout << "The last number in this range is: " << num << "\n";
    std::cout << "The sum of this range is: " << (total - num) << '\n';
    std::cout << "The number of items in this range is: " << x - 1 << '\n';
    std::cout << "The average of this range is: " << aver << "\n\n";
}

int main()
{
    const std::string prefix = "mynumberlist";
    const std::string suffix = ".txt";
    for(int i = 1; i <= 3; ++i) {
        statistics(prefix + std::to_string(i) + suffix);
    }
}
Topic archived. No new replies allowed.