### C++: Calculate average from file containing array of numbers?

I have written two separate programs; Program 1 calculates the average of an array of numbers which has been hard-coded into the program. Program 2 reads an array of numbers from a text file and displays them on the output.

I wish to combine these two programs into one by making Program 1 read the array of numbers from the file and then calculate the average using that instead of the array { 84, 92, 76, 81, 56 } as outlined below. I only wish to display the average in the output, not the number array as Program 2 does.

I have tried to do most of the work, I just need help with modifying the code slightly so it reads the number array from the file and calculates the average. Please include the modified code in your answer.

Program 1

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

int main()
{
const int nNumStudents = 5;
int anScores[nNumStudents] = { 84, 92, 76, 81, 56 };
int nTotalScore = 0;
for (int nStudent = 0; nStudent < nNumStudents; nStudent++)
nTotalScore += anScores[nStudent];

double dAverageScore = static_cast<double>(nTotalScore) / nNumStudents;

cout << "The average score was " << dAverageScore << endl;

getchar();
return 0;
}

Program 2

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream infile;
int nums[100];
infile.open("cnumbers.txt");

for (int i=0; i<10; i++){
infile>>nums[i];
cout<<nums[i]<< " ";
}
infile.close();
getchar();
return 0;
}
Last edited on

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream infile;
int nums[100];
infile.open("cnumbers.txt");

for (int i=0; i<10; i++){ // are you sure the input file contains only 10 integers?
infile>>nums[i];
cout<<nums[i]<< " ";
}
infile.close();
getchar();
return 0;
}
if not try this
 123456789101112131415161718192021222324 #include #include using namespace std; int main() { ifstream infile; int nums,total,x,aver; x=0; total=0; infile.open("cnumbers.txt"); while(!input.eof()) { infile>>num; total=total+num; x++; } aver=total/x; cout<
Last edited on
Yes, eof caused some issues in that it was including the last value twice in the average. In addition, the code that was provided needed some debugging, so the final version is below. Can someone come up with a more efficient method of doing this without eof?

#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("gnumbers.csv");

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';

infile.close();

getchar();
return 0;
}
Just loop on the std::cin statement itself:
 1234567891011121314151617181920212223242526272829303132 #include #include int main() { std::ifstream infile ("cnumbers.txt"); float num; float total = 0.0f; unsigned int count = 0; // While infile successfully extracted numbers from the stream while(infile >> num) { total += num; ++count; } // don't need the file anymore, close it infile.close(); // test to see if anything was read (prevent divide by 0) if (!count) { std::cerr << "Couldn't read any numbers!" << std::endl; return 1; } // give the average std::cout << "The average was: " << total/count << std::endl; // pause the console std::cin.sync(); std::cin.get(); return 0; }
Last edited on
Thanks, this worked like a charm. I was wondering if you could tell me how to loop through various files in this manner? e.g. we calculated the average for a file called enumbers.txt; suppose we wanted to calculate the average for a whole bunch of files, e.g. fnumbers.txt, gnumbers.txt, etc.

Is there anyway to do this through a loop without duplicating the code each time with a different file specified?
Also, suppose we wanted to calculate the percentage difference for each number and then store it as an array? What I am trying to do is create a model that can calculate the percentage differences between each subsequent variable, store it as its own array, and then calculate the skew from that using the formula ((n/(n-1)*(n-2))*(Xi-averageX)/standarddeviation^3)).

How do I store percentage changes as a separate array and then calculate the above for them with that formula?
Topic archived. No new replies allowed.