I've got a text file that looks something like this
44,12,4,5 2,45,3,1,2,45 6,77,5,3,5,44
I would like to use strtok() to separate this file into just numbers and read them into a char**, with spaces included, such that
arr[0] = "44"
arr[1] = "12"
arr[2] = "4"
arr[3] = "5"
arr[4] = " "
arr[5] = "2"
...
This is my code so far:
int i = 0;
char line[6000], **arr = calloc(200, sizeof(char*)), *token = calloc(50, sizeof(char)), *token2 = calloc(8, sizeof(char));
FILE* textFile = openFileForReading(); //Simple method, works fine.
fgets(line, sizeof line, textFile);
token = strtok(line, " ");
token2 = strtok(token, ",");
arr[i] = token2;
while((token2 = strtok(NULL, ",")) != NULL)
{
i++;
arr[i] = token2;
}
i++;
arr[i] = " "; //adds the space once we're done looping through the "word"
while((token = strtok(NULL, " ")) != NULL) //PROGRAM BREAKS HERE
{
token2 = strtok(token, ",");
i++;
arr[i] = token2;
while((token2 = strtok(NULL, ",")) != NULL)
{
i++;
arr[i] = token2;
}
i++;
arr[i] = " ";
}
At the beginning of the second while
loop, it's never executed. I'm sure it's got something to do with passing a NULL
argument into strtok, but I'm not sure really how to get around this. If any of you folks have advice, suggestions, or critique, I'd love to hear it.