I'm attempting to initialize an array from a list of numbers in a data file that looks similar to this:
1
4
7
12
...
96
There are 28 total numbers in the file. I'd like my array to look like the following:
arr[0] = 1
arr[1] = 4
arr[2] = 7
arr[3] = 12
The goal of this program is to use the array to find the standard deviation of the numbers in the file. I've tested to see if the rest of the code works with a manually filled array and it checks out, so all I need to know is how to get the numbers from the .dat file into my array.
My code so far is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
void input (double arr[], int& num)
{
int data;
ifstream fin;
fin.open ("project8.dat");
while (fin >> data)
{
int j=0;
arr[j] = data;
j ++;
num ++; // total number of integers in the array (so I can find the average)
// I'm not supposed to know how many numbers are in the data file
}
fin.close();
}
When I cout the array to check if the numbers were initialized properly, only arr[0] returns the last number in the file (96), and the rest of the array is filled with 0's. Please help me out if possible.
Also, yes this is for an assignment. My professor and textbook (that I've read as carefully as possible) don't explain this step.
Do I need to use something along these lines?
1 2 3 4 5 6 7 8
char ch;
while (fin.get (ch))
{
int j=0;
arr[j] = ch;
j ++;
num ++;
}
while (fin >> data) //get next data
{
int j=0; //initialize j to 0
arr[j] = data; //put data in array[0]
j++; //incremtent j
num ++;
}
//this is what happends throught out your input function.
//j is constantly byeing reinitialized to 0 and thus
//input goes in to override array[0].
//Hence, only the last item is in the array.
//send "int j = 0 " out before the loop