I'm reading in a .csv file (delimited by commas) so I can analyze the data. Many of the fields are null, meaning a line might look like:
456,Delaware,14450,,,John,Smith
(where we don't have a phone number or email address for John Smith so these fields are null).
But when I try to separate these lines into tokens (so I can put them in a matrix to analyze the data), strtok doesn't return NULL or an empty string, instead it skips these fields and I wind up with mismatched columns.
In other words, where my desired result is:
a[0]=456
a[1]=Delaware
a[2]=14450
a[3]=NULL (or "", either is fine with me)
a[4]=NULL (or "")
a[5]=John
a[6]=Smith
Instead, the result I get is:
a[0]=456
a[1]=Delaware
a[2]=14450
a[3]=John
a[4]=Smith
Which is wrong. Any suggestions about how I can get the results I need will be greatly welcomed. Here is my code:
FILE* stream = fopen("filename.csv", "r");
i=0;
char* tmp;
char* field;
char line[1024];
while (fgets(line, 1024, stream))
{
j=0;
tmp = strdup(line);
field= strtok(tmp, ",");
while(field != NULL)
{
a[i][j] =field;
field = strtok(NULL, ",");
j++;
}
i++;
}
fclose(stream);