The use of
while (!EOF)
is far from correct here. for one thing, EOF is a constant defined in <cstdio>, and does not really apply to the ifstream where the flags such as
inFile.good()
or
inFile.fail()
would be more relevant.
Also, checking the file status
before reading from it is not really useful, since the important thing the program needs to know is the file status
afterwards, which will indicate whether the data was read in successfully or not.
For example, the correct answers from the first line of the file could be read like this. Notice that the return type of the function is a
bool
which indicates whether or not the operation succeeded.
1 2 3 4 5 6 7 8 9
|
bool readarr(ifstream &in, double answer[])
{
for (int i = 0; i<20; i++)
{
in >> answer[i];
}
return in;
}
|
That function could be called like this:
1 2 3 4 5 6
|
bool ok = readarr(inFile, answer);
if (!ok)
{
cout << "error reading answers" << endl;
return 1;
}
|
The separate variable
ok
isn't strictly necessary, but it may help to show the logic more clearly.
Similarly, you could use a while loop which checks the result of reading the data for each student, before deciding to go ahead and calculate and output the grade.
My suggestion is to separate the reading of the file from the grade calculation, like this:
1 2 3 4 5 6 7 8
|
string id;
double studentAns[20];
while (readStudent(inFile, studentAns, id))
{
double reference = getgrade(answer, studentAns);
cout << id << " " << reference << endl;
outFile << id << " " << reference << endl;
}
|
Here, the function
readStudent()
reads the student id, then the 20 answers. It returns a
bool
in the same manner as function
readarr()
If the file access was ok, the body of the loop is executed, the grade calculated in function
getgrade()
and the result output.