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:

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.

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.

Recommended Answers

All 3 Replies

We need to know more... how does your find function work? what is an emp_data object? What is the problem with the code?

If your point is to ignore duplicate IDs, perhaps you need to keep a list in the function of all IDs that have been read and search that first. If it's the first time an ID has been read, then call the find function, otherwise skip the entry.

Ah, I actually figured out the issue. Ignoring invalid ID's were working just fine, what I was troubled with was adding a sum of hours worked when the same ID popped up twice. I originally, using the code above, was only able to stright up read the hours_worked and populate the array, but it would replace the fisrt entry for an ID number with the second, not add the two up.
My solution is below and thank you for your replies.

void get_timedata (ifstream& in, emp_data emp[], int n)

{
  int idnum; // stores the id number from the input file
  int x; // stores the position of the value in the array
  double hours_worked; // stores the hours worked from the input file
  double sum = 0; // stores the total hours worked for multiple ID entries

  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;

      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;
    }

  in >> idnum;
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.