Since you changed your tag to C, not C ++, I rewrote your function to use printf so you can see what is happening. Hoang is right. You see the correct result, but I think that you are printing everything on one line, so you are confused about the output. Look at Hoang's answer, explaining what is going on right. Also, as others have noted, strtok kills the input string, so you have to be careful about this - and it is not thread safe. But if you need a quick dirty tokenizer, it works. In addition, I changed the code to use strlen correctly and not sizeof as Anders correctly pointed out.
Here your code is modified to be more like C:
char* str = (char*) malloc(strlen("Madddy") + 1); strcpy(str,"Madddy"); char* tmp = strtok(str,"d"); printf ("first token: %s\n", tmp); do { tmp=strtok(NULL, "ay"); if (tmp != NULL ) { printf ("next token: %s\n", tmp); } } while(tmp != NULL);
source share