Hello, I'm having issues trying to parse a comma separated string...I can't seem to get past the spaces
I'm simply trying to parse a string that is as follows:
Code:
Date,Subject,Start Time,End Time,Location
Basically I want to end up with an array of strings containing each of the items that were separated by commas.
Here is my program...
Code:
int
main(void)
{
FILE *inp;
char *line;
int N = 10, M = 10;
int linemax = 256;
int i = 0, j = 0;
char **stringarray;
line = (char *)malloc(sizeof(char) *N);
stringarray = (char**)calloc(sizeof(char**), M);
inp = fopen("appts.csv","r");
fgets(line, linemax, inp);
printf("%s\n",line);
stringarray[0] = strtok(line, ",");
stringarray[1] = strtok(NULL, ",");
stringarray[2] = strtok(NULL, ",");
stringarray[3] = strtok(NULL, ",");
stringarray[4] = strtok(NULL, ",");
for(j; j < 6; j++) {
printf("%s\n", stringarray[j]);
}
return(0);
}
This is my output...
Code:
$ a.out
Date,Subject,Start Time,End Time,Location
Date
Subject
Sta )
Segmentation fault (core dumped)
How can I parse the string by commas? I know I should really be using strtok in a loop, but I'm trying to parse in the most simplest way possible before attempting to do anything more complex since I'm a beginner programmer.
Thanks in advance.