I tried parsing a string using strtok. When I initialized the string in the code itself it works as I expected.
#include <stdio.h>
#include <string.h>
int main()
{
char str[]="10 20 30";
char* token = strtok(str, " ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
output:
10
20
30
But when I get the input from the user, it prints only the first number.
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
printf("Enter the numbers.\n");
scanf("%s",str);
char* token = strtok(str, " ");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, " ");
}
return 0;
}
input/output:
Enter the numbers.
10 20 30
10
what is the reason for this?