Home > database >  strtok not splitting spaces correctly even with correct delimiter
strtok not splitting spaces correctly even with correct delimiter

Time:10-20

I am attempting to split two words (and more) and put them into an array by splitting it into tokens with strtok. My delimitors include " \t\n"; as shown below in the code. For example if I were to type in "cat program.c", it just prints the cat token and not the program.c token and I have no idea why. Are my delimitors not correct or am I not spitting the string correctly? Here is the code

  char b[100];
  int k = 0;
  char *args[4];
  char *tokens;
  char delimiters[] = " \t\n";
  printf("Please enter the command you want to use:\n");
  scanf("%5s", b);
  tokens = strtok(b, delimiters);
  while (tokens != NULL){
    args[k  ] = tokens;
    printf("%s\n",tokens);
    tokens = strtok(NULL, delimiters);
  }

CodePudding user response:

The problem is not strtok(), but rather scanf(). An %s field directive scans a whitespace-delimited string, so when the input is cat program.c, only the "cat" ever makes it into array b in the first place. (The program.c remains waiting to be read.) If you want to read a whole line of input at a time, then I would recommend fgets(), instead.

  • Related