0

Im working on an assignment that has this file provided to us as a students.csv file:

Boyd,An,903-04-2620,53583,54678,59414 
Chen,Andrew,995-52-6987,57056,56361,60360,58819 
Delgado,Chetan,992-63-3996,57056,60359,58820 
Hong,Frederick,992-84-9667,61802,57058,60360,58841 
Lee,Daniel,995-59-4469,61750,60189,60360,58890 
Li,Garret,995-65-9809,60853,60295,60360,59363 
Mangan,Janet,995-59-4760,60855,61367,59383 
McCullough,Jason,995-83-8060,51909,61626,61637,60364 
Ng,Joey,995-46-4586,57056,61670,61674,60364 
Park,Komal,995-50-9519,61702,59420

As you can see here, the data per line is last name, first name, student ID number, and then courses associated with that identification. I am able to read everything else in, except because the number of courses associated can vary, ideally from 0 to 5 (assignment has a cap on it), I am having trouble in how to recognize and parse the courses into my struct. Can someone simply suggest a way to read this in?

I am using the following code to read the rest in. I have commented out a section to fill in for reading in the courses

ptr = strtok(temp, ",");
(*students)[*count_stud].last = (char*) malloc(strlen(ptr)*sizeof(char));
strcpy((*students)[*count_stud].last, ptr)
ptr = strtok(NULL, ",");
(*students)[*count_stud].first = (char*) malloc(strlen(ptr)*sizeof(char));
strcpy((*students)[*count_stud].first, ptr);
ptr = strtok(NULL, ",");
strcpy((*students)[*count_stud].ssid, ptr);
/*while(ptr = strtok(NULL, ","))
{
}*/ //end while crn strtok
(*count_stud)++;

Here is my struct, I have figured out everything but crn[6] and count_classes.

typedef struct
{
  char* first;
  char* last;
  char ssid[15];
  int crn[6];
  int count_classes;
}Student;

I have declared the struct as follows and then used malloc appropriately (I am not to use malloc for the crn's)

Student *students=NULL;

1 Answers1

0

Yes you are on the right track using strtok

By checking the return value strtok you can determine optional parts of the string, since the first three fields are mandatory you can do

Student* s = calloc( 1, sizeof(Student) ); // allocate new student
s->last = strdup( strtok(temp, ",") ); // allocate and copy
s->first = strdup( strtok(NULL, ",") ); 
strcpy( s->ssid, strtok(NULL, "," ) );

since you say there can be only max five courses you would need say five long ints to hold those in your struct, but ok if you want to have six.

you need to convert the strings to integers

char* course = NULL;
while ((course = strtok(NULL,",")) != NULL && s->count_classes < 5)
{
  s->crn[s->count_classes++] = atoi( course );
}

the above code reads one Student record, I will leave it to you to make an array (or linked list) of the records. Hint: realloc() instead of calloc() but don't forget to initialize contents.

AndersK
  • 35,813
  • 6
  • 60
  • 86