fstream into a struct?

I do not know how to get my data into my struct. I know how streams work and how to get my info but i can not get them to work with a struct

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
struct grade_t {
	int id;
	int score;
	string grade;
};

void readStuData(
	ifstream& rss,			//IN: data file, must already be opened
	grade_t students[],		//OUT: the student record
	unsigned int& count,  	//OUT: Number of students read
	bool& tooMany			//A flag to indicate that more then MAX_SIZE students are in input file
	)
{
	int counter = 0;
	while (!rss.eof())
	{
		rss >> students[counter].id >> students[counter].score;
		counter++;
	}
	count = counter + 1;

	if (count > 100)
	{
		tooMany = true;
	}

}
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

Last edited on
Topic archived. No new replies allowed.