I almost have a project done where I have to create a data file, write to it, read from it, then find things like the sum, average, and standard deviation. However, our professor also stated that if he uses his own num.dat file (already created) it has to be able to read that as well. My code will read from it one but after that it will not, and I'm not sure why. It could be that I am using the inFile as a reference variable, but I am not sure. Here are the pieces of code i believe could be the problem:
This is in main:
1 2 3 4
cout<< "Reading data from file\n";
int datarray[100];
arraylength = readFile (inFile, datarray);
cout<<"The number of elements in the array is "<< arraylength<<endl;
int readFile (ifstream &inFile, int datarray[])
{
int size = 0;
inFile.open("num.dat");
if (inFile.is_open())
{
while (size < 100)
{
inFile>> datarray[size];
if (!inFile)
break;
cout<< datarray[size]<<" ";
size++;
}
cout<<endl;
inFile.close();
return size;
}
else
{
cout<<"Could not open.\n";
return -1;
}
}
As I stated, if I create or manipulate "num.dat" within the menu of my main function it works. But if the file is already made, it won't. Any input and help is greatly needed, and appreciated.