Hello. My goal is to read data 6 pieces of data from a file, with the first piece of data declaring how many other pieces of data are in the file. For example, my data is 5 10 20 -30 0 40, with the 5 meaning there are 5 pieces of data. On to the problem. My goal is to read this data and determine the mean, which I can do without trouble. The trouble comes in when I need to use the mean to figure out the standard deviation of the numbers. Basically, the standard deviation is the sum of each of the data minus the mean, squared. So, (10-8)^2 + (20-8)^2 + (-30-8)^2 + (0-8)^2 + (40-8)^2. This sum will then be divided by the number of data minus one, so four. This will then be square rooted. However, when I get to the second while loop, and I try to sum the points minus the mean, I am getting 0 as an output. Here is what I have. If anything is confusing, let me know and I'll try to make it less confusing.
#include <fstream>
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
ifstream inFile;
int n, x, sum, mean, sumOfDifference;
inFile >> n; // Number of values in file
sum = 0;
inFile >> x; // Read data
while(inFile)
{
sum += x; // Sum values in file
inFile >> x; // Read data
}
mean = sum/n; // Average of data in file
cout << "The mean of the numbers is " <<
mean << "." << endl;
inFile >> n; // Number of values in file
inFile >> x; // Read data
sumOfDifference = 0;
while(inFile)
{
sumOfDifference += (x-mean)*(x-mean);
inFile >> x;
}
It looks like you are trying to read the same file twice without closing it. Put your data in an array or a vector. I suggest you test your inFile before each while loop and you will see what is wrong.
Thanks for responding. However, I have not learned arrays yet and would like to do it like it is. So you are saying that I should close it after the first while loop and then open it again and it should work?