0

CVS Example:

Month,usg_apt,fg_apt,carrier,type,Scheduled
6,JFK,LHR,VS,Passengers,85790
1,JFK,CDG,AF,Passengers,85324
4,LGA,YYZ,AC,Passengers,82389
6,JFK,LHR,BA,Passengers,79975

The struct I created for it:

typedef struct RouteRecord
{
  char origin[4];      //second column
  char destination[4]; //third column
  char airline[3];     //fourth column
  int passengers[6];   //last column ,[0] is January, [1] is February......
}RouteRecord;

The first column is the month, and the last column is the quantity. I want to allocate the quantity to the Index of the corresponding Array according to the corresponding month, so how should this be implemented?

for example, if we have RouteRecord* r first-line first item is 6,so r.passengers[5] = 85790

Here is what I got so far:

int fillRecords( RouteRecord* r, FILE* fileIn )
{
  r = createRecords(fileIn);

  //skip first line
  char buffer[100]= (char*)malloc(100*sizeof(char));
  fgets(buffer, 100, fileIn);
  
  //read file
  int i = 0;
  int length = 0;
  int count = 0;
  while(!feof(fileIn))
  {
    //check length of airline
    length = strlen(r[i].airline);
    if(length>=3)
    {
      fgets(buffer, 100, fileIn);//skip a line
      count--;
    }

    //fill for passenger with month
    int month;
    char* tempStr = (char*)malloc(1024*sizeof(char));
    fscanf(fileIn,"%d,%[^,],%[^,],%[^,],%[^,],%d",&month,r[i].origin,r[i].destination,r[i].airline,tempStr,&r[i].passengers[0]);
    i++;
    count++;
  }
  return count;
}

Thank you So much for your help!

Jason
  • 1
  • 1
    `char buffer[100] = (char*)malloc(100*sizeof(char));` you declared an array and try to `malloc` it , which is wrong, just use `char *buffer` – csavvy Nov 01 '20 at 05:37
  • Also there are few points 1) you are trying to extract information from the same line why do you want to skip the lines 2) I think you need to extract information based on the separator of fields like `,` for instance here 3) you can read a line first then try reading all characters till you see `,` and store fields into other variables – csavvy Nov 01 '20 at 05:49
  • You will want to look at [**Why is while ( !feof (file) ) always wrong?**](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) Also, `int passengers[6];` is too-few-by-1 if you want to store the month as the 1st char and then treat quantity as the last 5 characters and use it as a *string* (where would `'\0'` go?) – David C. Rankin Nov 01 '20 at 09:18

0 Answers0