So my shell project has been coming along, but my latest speedbump is introducing user input. I’m trying to tokenize an input string, but after the first token strtok only returns NULL. But if I hard-write the string in the program, everything works flawlessly. How I can I treat the user input so that strtok will tokenize the whole string (instead of the first)?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char input[100];
scanf("%s", input); //input entered is "echo 1 2 3 4"
char *temp=strtok(input, " "); //this is "echo"
printf("temp1: %s\n", temp);
temp=strtok(NULL, " "); //this is (null)
printf("temp2: %s\n", temp);
}
The problem is with
scanf("%s"...)which stops reading at the first whitespace character and returns the string. In other words,scanf("%s"...)will not read more than one word.See here under ‘%s’: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
scanf("%[^\n\r]", string_variable)might be a better idea.Update: As mentioned by Seth in the comments,
"%[^\n\r]"means read all characters until any of the characters after the^is encountered.