Tehreem Tehreem - 4 months ago 25
C Question

Why is strtok printing only first word?

I am using strtok for converting string into individual words. I have done the following:

int main() {
char target[100];
char *t;
scanf("%s",target);
t = strtok(target," ");
while (t!= NULL)
{
printf("<<%s>>\n", t);
t = strtok (NULL, " ");
}
return 0;
}


The input is a string such as 'this is a string', the output I am getting is
<<this>>
.

Answer

The way you have written scanf it will accept string till white space only

scanf("%s",target);

SO You need to change the way you take input from console

scanf("%99[^\n]",target);