Array / While Loop / Sum Question

I have a void function that takes data from an ifstream, reads the first value, (which is an ID #), and compares that value against the ID# info from an array of records. If it's invalid, the rest of the line is ignored. If it's valid, it adds the hours worked to the hours worked field in an array of records. Here is what the input file looks like:

1
2
3
4
5
123 7.5
56 6.25
99 an invalid id
555 2.5
123 10.0


My issue is there is the possibility of multiple entries for the same ID# and for the life of me I cannot figure out how/where to place that in my while loop.

Can anyone steer me in the right direction? Code for the function is below.

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
void get_timedata (ifstream& in, emp_data emp[], int n)
{
  int idnum;
  int x;
  double hours_worked;

  in >> idnum;

  while (in)
    {

      x = find(emp, n, idnum);

  if (idnum!=emp[x].idnum)
    in.ignore(100,'\n');

  if (idnum==emp[x].idnum)
    {
      in>>hours_worked;
      emp[x].hours_worked = hours_worked;
    }

  in >> idnum;
    }
}


Thanks in advance.
Last edited on
emp_data constructor initializes hours_worked to 0, doesn't it?

Then you could add rather than set, assuming the idea is to sum up the multiple hour entries.
Ah, I figured it out. See, I had to be able to have a running total if the input file happened to throw multiple entries for the same ID number. I figured it out by finding the right spot to add an additional "if" statement to the above function:



1
2
3
4
5
6
7
8
9
10
11
12
if (idnum==emp[x].idnum)
    {
      in >> hours_worked;

      if (emp[x].hours_worked > 0)
	{
	  sum = emp[x].hours_worked + hours_worked;
	  emp[x].hours_worked = sum;
	}
      else
	emp[x].hours_worked = hours_worked;
    }


Thanks for your help.
emp[x].hours_worked += hours_worked;
That does the same as your if-else on lines 5-11.
Topic archived. No new replies allowed.