Hello guys, i tried to use strtok but without success..
I have a simple file with 2 lines:
1) hello, world
2) loving, programming
I would like to save all words in a different position of a 2D array, like this
arr[0] = hello, arr[1] = world, arr[2] = loving, etc...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
void print_char_array(char **a, int size);
int main(int argc, char const *argv[])
{
int size = 4;
int _char_index = 0;
char **_char_arr = (char **)malloc(size * sizeof(char *));
char *pch; //token for strtok
FILE *_file = fopen("/Users/vitto/Desktop/Untitled.txt", "r");
char *line = (char *)malloc(100 * sizeof(char)); //each file's line will be saved here
while (fscanf(_file, "%[^\n]", line) != EOF)
{
getc(_file);
printf("Line: %s\n", line);
pch = strtok(line, ",");
while (pch != NULL)
{
_char_arr[_char_index] = pch;
_char_index++;
pch = strtok(NULL, ",");
}
}
print_char_array(_char_arr, size);
free(_char_arr);
return 0;
}
void print_char_array(char **a, int size)
{
int i;
printf("ARR: ");
for (i = 0; i < size; i++)
printf("%s ", *(a + i));
printf("\n");
}
|
But the output is always the same:
Line: hello, world
Line: loving, programming
ARR: loving loving programming
Program ended with exit code: 0
//////////////////////////////////
It has a weird behavior.. it prints 2 "loving" and 1 time "programming"...??
Did i miss something with STRTOK or im doing wrong with 2D pointers?.. im lost.
Thank you all for the help.