I try the understand the relation 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 as possible whitespace (Enter, Blanks, Tabs) after I type in a number like 54 and press enter.
As far as I understand every key which I press is put in the input buffer until I press Enter.
So if I type in 54 and press Enter the input buffer contains 3 elements, two digits and the line break. So my buffer looks like [5][4][\n]
Now scanf/formatstring is evaluated from left to right. So the first %d matches to 54, 54 is stored in z1.
Because of the whitespace in the format string the line break (\n) caused from pressing the first enter is "consumed".
So after the evaluation of the first %d and the whitespace (\n) the buffer is empty again.
Now scanf tries to evaluate the second (and last) %d in the format string. Because the buffer is now empty scanf waits for further user input (user input = reads from stdin in my case keyboard).
So the buffer state/action sequence is
buffer empty -> call of scanf -> scanf blocks for user input --> user input is: 54 Enter --> buffer contains: [5][4][\n] -> evaluation of first %d --> buffer contains [\n] -> evaluation of whitespace --> buffer empty --> scanf blocks for user input (because of the evaluation of second and last %d) --> ...
Did I understand this correct? (sorry, english is not my native language)
regards
prog < prepared-inp.txt
which works similar in a Windows command shell and the various linux shells. – Peter - Reinstate Monica%d
format rightly skips all white space it encounters because it's only interested in numbers. White space in the format string is only significant for%c
and%[...]
(which would otherwise assign it to their corresponding arguments). – Peter - Reinstate Monicasetbuf()
), but you could disable that!) The interesting thing is the sequence of characters whichgetchar()
sees. Where exactly they come from and whether they were buffered somewhere is secondary. – Peter - Reinstate Monica%n
. – Spikatrix%n
in the format? True. Of course ;-). – Peter - Reinstate Monica