This question already has an answer here:
- Using strtok() in a loop in C? 3 answers
I have a string like this:
a;b;c;d;e
f;g;h;i;j
1;2;3;4;5
and i want to parse it element by element. I used nested strtok function but it just splits first line and makes null the token pointer. How can i overcome this? Here is the code:
token = strtok(str, "\n");
while(token != NULL && *token != EOF)
{
char a[128], b[128];
strcpy(a,token);
strcpy(b,a);
printf("a:%s\n",a);
char *token2 = strtok(a,";");
while(token2 != NULL)
{
printf("token2 %s\n",token2);
token2 = strtok(NULL,";");
}
strcpy(token,b);
token = strtok(NULL, "\n");
if(token == NULL)
{
printf("its null");
}
}
Output:
token 2 a
token 2 b
token 2 c
token 2 d
token 2 e
You cannot do that with
strtok()
; usestrtok_r()
from POSIX orstrtok_s()
from Microsoft if they are available, or rethink your design.These two functions are interchangeable. Although
strtok_s()
is an optional part of C11 (Annex K in ISO/IEC 9899:2011), few suppliers other than Microsoft have implemented the interfaces in that section of the standard.With strtok_r()
Results
Without strtok_r()
This works in context - provided that the data ends with a newline.
Output
strtok_r
is the best and safest solution, but there is also a way to do it withstrtok
:Output: