Reputation: 73
Basically I have to tokenise a 4 column line and put those tokens into an array, and so I made this function below.
char** tokeniser(char* lineToToken)
{
int i = 0;
char** tokenList = malloc(4*sizeof(char*));
char* token;
while ((token = strtok(lineToToken, " ")) != NULL && i<4)
{
tokenList[i] = malloc(strlen(token) + 1);
strcpy(tokenList[i], token);
++i;
}
return tokenList;
}
and in the main I have this simple thing to test it, and only get first element printed 4 times..
for(int i = 0; i<3; i++)
{
printf("%s", tokenList[i]);
}
the text file that I put this through is "asda asdasd 23 asd", but I only get asda 4 times :S
Upvotes: 1
Views: 790
Reputation: 11
In the above function every time Strtok function you are passing the start address of the same string.
Generally strtok function should be called in the following manner.
#include<stdio.h>
#include<string.h>
void main() {
char Src[25]="Hare Krishna Hare Rama";
char C[2]=" ";
char *del=C;
char *temp[5];
int i=0;
temp[i] = strtok(Src,del);
while(temp[i] !=NULL) {
printf("The str is <%s\n>",temp[i]);
temp[++i] = strtok(NULL,del);
}
}
When you are calling first time you have to pass the start address of the string and delimiter. Then strtok returns start pointer which point to the delimiter.So next time when you call you no need to pass the start address of the string, strtok will remembers the address which point to next character of the delimiter.So Subsequent calls should be called with NULL pointer.
Upvotes: 1
Reputation: 4176
The issue is in your usage of strtok()
. The documentation from cplusplus.com says it best:
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
In summary, you are passing the string to be tokenized over and over, rather than passing it the first time only (and NULL
subsequent times)
So, the following program might give you the example that you need:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char** tokeniser(char* lineToToken)
{
int i = 0;
char** tokenList = (char**) malloc(4 * sizeof(char*));
char* token = strtok(lineToToken, " ");
while(token != NULL && i < 4)
{
tokenList[i] = (char*) malloc(strlen(token) + 1);
strcpy(tokenList[i], token);
token = strtok(NULL, " ");
++i;
}
return tokenList;
}
int main(int argc, char const* argv[])
{
char str[] = "asda asdasd 23 asd";
char** tokenList = tokeniser(str);
for(int i = 0; i < 4; ++i)
{
printf("%s\n", tokenList[i]);
}
return 0;
}
On my machine this prints:
asda
asdasd
23
asd
Upvotes: 3