Question

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;
}
Was it helpful?

Solution

First of all, you want to use strtol instead of atoi (or sscanf, see below). The function atoi is unsafe.

Second, strtok needs NULL instead of string:

pointerToDateStructure->day = atoi(strtok( string, delim));
pointerToDateStructure->month = atoi(strtok( NULL, delim)); /* NULL instead of string. */
pointerToDateStructure->year = atoi(strtok( NULL, delim)); /* See above. */

Third, you are not checking the value returned by strtok.

As a side note, are you sure sscanf can't parse your data ?

sscanf(str, "%d/%d/%d", &day, &month, &year)

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.

OTHER TIPS

sscanf(str, "%02d/%02d/%[^\n], &day, &month, &year) is the one of the easiest options, but you should be precise with the format; otherwise everything will go wrong.

If you really want to use strtok(), use it in the exact way as cnicutar said but be precise with verification at each step.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top