-
strtok problem
i write a strtok program, i think should be got some errors but i cant figure it out why.Can anyone please tell me what is the problem of my program? Thanks for helping.
My program need to convert the string into 1-dimesion array, but it fails.
Code:
int main(void){
char words[20][20] = {"we are happy.", "happy,", ",friday." };
int i, j;
char delim[] = ",.";
char *result;
for ( i=0; i<20; i++){
for( j=0; j<20; j++){
result = strtok( &words[i][j], delim);
while( result != NULL){
printf("%s\n", result);
result = strtok(NULL, delim);
}
}
}
}
My Output Supposed to be :
we
are
happy
happy
friday
But after compile my program above, my output is:
we
are
happy
we
e
are
re
e
happy
appy
ppy
py
y
happy
appy
ppy
py
y
friday
riday
iday
day
ay
y
what is the program error ar? i cant figure it why@
-
You're running two loops and going through every character. Totally wrong. Only one for loop for each string, not for each char.
Also, you should include the space char inside delim.
Try something like this (can't say for sure it works):
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char words[20][20] = {"we are happy.", "happy,", ",friday." };
int i;
char delim[] = ",. ";
char *result;
for ( i=0; i<20; i++)
{
result = strtok(words[i], delim); /* Make sure you understand what goes on in here! */
while(result != NULL)
{
printf("%s\n", result);
result = strtok(NULL, delim);
}
}
return 0;
}