0

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?

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
sivaram
  • 59
  • 5
  • 5
    The `%s` format for `scanf` reads *space-delimited* "words". If you want to read a whole line use [`fgets`](https://en.cppreference.com/w/c/io/fgets). – Some programmer dude Sep 12 '21 at 07:19
  • 2
    You can also use `scanf("%[^\n]s",str);` for reading until a newline character (`\n`). https://stackoverflow.com/a/8097776. However, as per this link https://stackoverflow.com/a/17294869 using `fgets()` is safer. – kiner_shah Sep 12 '21 at 07:21
  • but when I use fgets the newline character gets added to the last number and a newline is printed at the last. How can I prevent that? – sivaram Sep 12 '21 at 07:25
  • 4
    @kiner_shah You don't need the `s` after `%[^\n]` in the `scanf()`, read [this aswer](https://stackoverflow.com/questions/45876377/what-is-the-difference-between-scanf-s-a-scanf-ns-a-and-getsa-for/45876672#45876672). I also recommend doing `scanf("%99[^\n]",str);` to avoid buffer overflow. – JASLP doesn't support the IES Sep 12 '21 at 07:34
  • Thanks @JustASimpleLonelyProgrammer, learnt something new :-) – kiner_shah Sep 12 '21 at 07:36
  • 2
    @sivaram You remove the trailing newline from the string you read. `str[strcspn(str, "\n")] = '\0';` is one common way. – Shawn Sep 12 '21 at 10:17

0 Answers0