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?
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';
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);
}
}