I’m having trouble using the strtok() function. I feed this a date of 01/01/2000; my
expected output is: 1, 1, 2000; however I’m just getting 1, 1, 1.
Why is that?
#include <stdio.h>
#include <stdlib.h>
#include "date.h"
#include <string.h>
struct date{
int day;
int month;
int year;
};
Date *date_create(char *datestr){
printf("inside date_create");
char delim[] = "/";
Date* pointerToDateStructure = malloc(sizeof(Date));
printf("%s",datestr);
char string[10];
*strcpy(string, datestr);
pointerToDateStructure->day = atoi(strtok( string, delim));
pointerToDateStructure->month = atoi(strtok( string, delim));
pointerToDateStructure->year = atoi(strtok( string, delim));
printf("%d", pointerToDateStructure->day);
printf("%d", pointerToDateStructure->month);
printf("%d", pointerToDateStructure->year);
return pointerToDateStructure;
}
First of all, you want to use
strtolinstead ofatoi(orsscanf, see below). The functionatoiis unsafe.Second,
strtokneedsNULLinstead ofstring:Third, you are not checking the value returned by
strtok.As a side note, are you sure
sscanfcan’t parse your data ?EDIT Explanation by abelenky:
The function strtok has state. It “remembers” what string it was working on before, and if you pass “NULL”, it continues to work on that same string, picking up where it stopped before. If you pass it a string parameter each time, it starts at the beginning each time.