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

拟墨画扇 提交于 2021-01-27 17:42:38

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/38039634/does-scanf-function-ignore-the-enter-key-when-looking-for-d-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!