I am writing my own strtok function. How do I make it so that it will return the remaining string as an output parameter?
Here is what I made so far.
char *mystringtokenize(char **string, char delimiter) {
static char *str = NULL;
int stringIndex = 0;
if (string != NULL) { //check if string is NULL, if its not null set str to string
str = string;
}
if (string == NULL) { //return NULL if string is empty
return NULL;
}
do { //traverse through string
if (!str[stringIndex]) { //if str at string index is null character, stop while loop
break;
}
stringIndex++;//index through string
} while (str[stringIndex] != delimiter);
str[stringIndex] = '\0'; //cut the string
char *lastToken = str; //set last token to the cut off part
return lastToken;
}
When I call it in main, and try to pass in the file that needs to be tokenized, I get a bad exception error.
int main(int argc, char const *argv[])
{
FILE *inputStream = fopen("FitBitData.csv", "r");
int index = 0;
int fitbitindex = 0;
char testline[100];
char minute[10] = "0:00:00";
FitbitData fitBitUser[1446];
if (inputStream != NULL) {
while (fgets(testline, sizeof(testline), inputStream) != NULL) {
strcpy(fitBitUser[fitbitindex].patient, mystringtokenize(testline, ','));
strcpy(fitBitUser[fitbitindex].minute, mystringtokenize(NULL, ','));
printf("%s %s\n", fitBitUser[fitbitindex].patient, fitBitUser[fitbitindex].minute);
printf("%s\n", fitBitUser[fitbitindex].patient);
fitbitindex++;
}
}
return 0;
}
For example, when I have a line Hello, World and tokenize it. It will return Hello. But If I call it again mystringtokenize(NULL, ','), it returns a bad exception error.