Search code examples
cwhitespacescanfformat-specifiers

Does Scanf function ignore the Enter key when looking for %d match?


I'm new to to C language and I'm studying it on a book by Kim N. King. It say that the scanf() looks for number pattern ignoring the whitespaces but I think it also skips on Enter key. While if it looks for characters it obviously takes the whitespace also.

Therefore in this example code I have to use getchar() to clear the stream before the second scanf(), otherwise the second one would be executed without waiting for user's input.

printf("Enter a char: ");
scanf("%c", &ch1);
getchar();
printf("\nEnter another char: ");
scanf("%c", &ch2);

If I look for digits instead, I have no problems.

printf("Enter a number: ");
scanf("%d", &n1);
printf("\nEnter another number: ");
scanf("%d", &n2);

Is my assumption (It skips the Enter key) right?


Solution

  • Pressing ENTER key inputs a newline (\n), which is a whitespace character.

    Quoting C11, chapter §7.21.6.2, fscanf()

    A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps:

    1. Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier. [....]

    So, yes, any leading whitespace (present in the input buffer) is (are) skipped or ignored for %d.