0
votes

I was fiddling with C and happen to wrote code below. When I input a string with spaces, program receives all of the input but outputs them as if they were inputted as single words at different times. I thought scanf stopped when first whitespace character is encounterd and ignored the rest. But that seems, is not the case.

I included the output when I enter "inputWithNoSpaces" and "input with spaces", below.

I tried to look into stdin. It receives all the input. But I could not figure out what scanf was doing. I would like to learn what is happening.

Code:

#include <stdio.h>

int main()
{
    int i=0;
    char word[64]="";

    while(1)
    {
        printf("enter string:");
        scanf("%s",word);
        i++;
        printf("%d:%s\n\n",i,word);
    }

    return 0;
}

Output:

enter string:inputWithNoSpaces
1:inputWithNoSpaces

enter string:input with spaces
2:input

enter string:3:with

enter string:4:spaces

enter string:
1
Don't use scanf for string, use fgets.Jabberwocky
Please be aware that stdio buffers whole lines of input. Scanf does not read from keyboard; it reads from that buffer.Ruud Helderman

1 Answers

2
votes

In scanf(), "%s" means "skip whitespace characters then read a sequence of non-whitespace characters". So when you give it the input input with spaces it will return "input", "with" and "spaces" in three sequential calls. That is the expected behavior. For more information read the manual page.

input with spaces
^^^^^                    First scanf("%s", s) reads this
     ^                   Second scanf("%s", s) skips over this whitespace
      ^^^^               Second scanf("%s", s) reads this
          ^              Third scanf("%s", s) skips over this whitespace
           ^^^^^^        Third scanf("%s", s) reads this