I am trying to understand the relationship between scanf and the input buffer. I use scanf with the following format string:
int z1,z2; scanf("%d %d", &z1,&z2);
And try to understand why I can enter as many spaces as possible (Enter, Blanks, Tabs) after entering a number like 54, and press enter.
As far as I understand, each key that I press is placed in the input buffer until we press Enter.
So, if I type 54 and press Enter, the input buffer contains 3 elements, two digits and a line break. Therefore, my buffer looks like [5] [4] [\ n]
Now scanf / formatstring is evaluated from left to right. Thus, the first% d corresponds to 54, 54 is stored in z1.
Due to a space in the format string, line break (\ n) caused by pressing the first input is "consumed".
So, after evaluating the first% d and the space (\ n), the buffer is empty again.
Now scanf is trying to evaluate the second (and last)% d in the format string. Since the buffer is now empty, scanf waits for further user input (user input = reading from stdin in my keyboard).
Thus, the sequence of states / actions of the buffer
buffer empty β call scanf β scanf blocks for user input β user input: 54 Enter β buffer contains: [5] [4] [\ n] -> evaluate the first buffer% d β contains [\ n] -> space estimate β buffer empty -> scanf blocks for user input (due to evaluation of the second and last% d) -> ...
I got it right? (sorry, english is not my native language)
considers