Solve one problem, run into another... anyway I have another question. I am trying to write an array to a data file then read it and tell the size back. The creating array and saving it was easy. But I cannot get my function to read the array and return the size. Here is my code (call and function, respectively):
cout<< "Reading data from file\n";
ifstream inFile;
int datarray[100];
arraylength = readFile (inFile, datarray);
cout<< arraylength<<endl;
int readFile (ifstream &inFile, int datarray[])
{
int size;
inFile.open("num.dat");
if (inFile.is_open())
{
for (int i = 0; i < size; i++)
{
inFile >> datarray[i];
cout<< datarray[i];
}
inFile.close();
return size;
}
else
{
cout<<"Could not open.\n";
return -1;
}
}
Well actually, our teacher wants the number of elements in the array back. Which is stupid if you ask me since the function before this lets the user chose the size... but I am not a college professor.
That's beside the point. You declared int size; but you didn't do anything to it. So when you get to for(int i = 0; i < size; i++) you don't have any specific number of times that you're going to go through the loop. It's not storing any meaningful value.
Well I was looking for that and a came across feof but that requires pointers... which I am not allowed to use yet because our class hasn't gone over them.
I'm positive that there are eof functions that you can use to determine the end of a file. You may want to consider ditching the whole idea of a for loop, and use some other type of iteration.
Well there is also the problem of finding the sum and average. I have functions that take each element of the array to find sum and average, but how do I get them out of the file and transfer them to these functions?
Test for .eof() before you display... otherwise, your final output will be an unintended result. I might do something like this:
1 2 3 4 5 6 7 8 9 10
int size=0;
while(size<100) { //your array size is 100 (index: 0-99)... protecting from overrun
inFile >> datarray[size]; //read file
if(!inFile) break; //essentially, read into the array until .eof() or other failure
cout << datarray[size]; //display what you read
size++;
}
That worked! Thank you. That really helped me understand how to end the file. However, when I need to get all the array elements out to add, would I need a readFile function similar to pull out each element for addition? I have to have this function, with these inputs:
int computeSum (int num[], int size)
{
int total = 0;
for (int i = 0; i < size; i++)
total = total + num[i];
return total;
}