c - Taking input and splitting into tokens repeats -


so have simple function takes in input , prints hello every time function run.

void takeinput(void) {      char *ptrfirst;     char input[50];     scanf("%s", input);     ptrfirst = strtok(input, " ");      printf("hello"); }  int main(int argc, char** argv) {      while(true) {         takeinput();     }      return 0; } 

if put input "1 2 3 4" word "hello" printed 4 times. assumed function print hello once, accept more input. why happening?

if put input "1 2 3 4" word "hello" printed 4 times. assumed function print hello once, accept more input. why happening?

the scanf() conversion specifier %s reads a sequence of non-whitespace characters.

so takeinput() called, enter "1 2 3 4", scanf() processes 1, , function returns.

it called 3 more times, processing 2, 3, , 4 still in input buffer.

then function called fifth time, , waiting input.

at no point input tokenized strtok(), because input never contains whitespace begin with.

you looking fgets( input, 50, stdin ) read whole line of input. (check presence of \n @ end make sure captured whole input.)


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -