Most of the ingredients are there, it's a matter of putting them together in the right order.
Often a program is required to either read until there is no more data in the file, or until an array has been filled. Your program is a little more complicated because of the flag
bool & tooMany
. In order to set that correctly, you would need to continue reading one more time after the array has been filled (in order to discover whether or not the file does indeed contain too many values).
Most importantly, don't use
eof()
as the condition in a loop. It can give rise to various errors. Your code shows one of them.
At line 17, an attempt is made to read an id and score from the file. There is no check on whether that file access managed to read anything. The counter is incremented at line 18 even if the read failed.
A better approach is to put the input statement itself in the loop condition.
1 2 3 4
|
while (rss >> students[counter].id >> students[counter].score)
{
counter++;
}
|
Above, the counter is incremented only when the file was successfully accessed.
That's a rough idea. But it isn't sufficient here.
We need to account for two additional things, the limited size of the array, and the setting of the toomany flag.
Line 11 states in the comment, "A flag to indicate that more then MAX_SIZE students are in input file". But line 22 uses some other number, 100 in order to test whether there were too many entries. I'd recommend using the constant MAX_SIZE rather than so-called magic numbers such as 100 which are difficult to track and maintain.
Pseudocode
define a temporary grade_t variable named student.
Set count to zero.
Set toomany to false.
read from the file into the student variable.
if count < MAX_SIZE
copy student to students[count]
increment count
else
set toomany to true
exit from loop |