Reputation: 13
i have tried using strtok function but i dont know how to use it
this is the code i read from the net
FILE *ptr = fopen("testdoc.txt", "r");
char nums[100];
fgets(nums,100,ptr);
const char s[2] = ",";
char *token;
token =strtok (nums, s);
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, s);
}
why do we have token = strtok(NULL,s) in the last line?? and how do i store the numbers obtained by token into an array?? thanks alot, please explain in detail
Upvotes: 1
Views: 84
Reputation: 375
strtok changes its first argument (contents of char*/char[]). When it finds first seperator(second argument) from char array, the seperator in the array is changed to '\0', and a char* is returned. After this, when you want to get second segment, you should use NULL as first argument (strtok has already hold the array, don't drop them), and strtok finds next seperator, change it to \0, and return this segment by char*(to first char of this seg).
To second question, change char* to int:
int i = atoi(strtok(...));
Upvotes: 0
Reputation: 1979
From strtok reference
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
That is strtok
stores the position internally.
It's pretty simple to get the numbers of obtained tokens. There are no miracles. Just use counter
and increment it in a loop.
Upvotes: 1