First question
I mean when they skip scanf, and when they don't
Space characters are skipped if the format specifier is %c , %n or %[ . Corresponding quote from standard C11:
7.21.6.2 fscanf function
[...]
- Entering space characters (as indicated by
isspace ) is skipped if the specification does not include the [ , c or n specifier. 284)
How are they skipped?
Just read and discard them.
Second question
I also can not understand the function scanf?
scanf is a variational function , which means that it can take any number of arguments with at least one. scanf parses the first argument, which is a string literal and, accordingly, accepts input.
Third question
But when I replace the variable char ch with int ch, scanf skips the new line. Why?
The first part of the first answer explains this. %d skip whitespace.
Fourth question
Why does scanf not skip non-white spaces like spaces?
For some conversion specifiers, such as %c , characters without spaces are valid entries. It makes no sense why they should skip them. For others, such as %d , characters (not numbers) are invalid entries. scanf stops scanning and returns when it sees an invalid input. It is designed that way.
Fifth question
What is the difference between space and newline in scanf?
It makes no difference if any of them fit in a format string in scanf . Both are considered space characters , although they are different. They skip any number of whitespace characters, including none, to the first character without a space when they are used in a scanf format string. Corresponding quote from standard C11:
7.21.6.2 fscanf function
[...]
- A directive consisting of white space character (s) is executed by reading the input up to the first character of a non-white space (which remains unread) or until more characters are read. The directive will never work.
Cool guy
source share