问题
Does the input buffer gets cleared after scanf
reads?
#include <stdio.h>
int main(void)
{
int a, b;
scanf("%d", &a);//I inputted 3
scanf("%d", &b);//I inputted 4
}
So when I gave the input 4
was 3
present in the input buffer?
回答1:
So when I gave the input 4 was 3 present in the input buffer?
No, the 3 was consumed.
You cannot re-read it (as int or otherwise).
If you input "3<enter>"
the 3 is consumed and the buffer contains just the "<enter>"
. You then type "4<enter>"
which is added to the buffer. The 2nd scanf (*) consumes the initial enter and the 4 leaving "<enter>"
for the next input operation.
(*) the conversion specifier "%d"
skips optional leading whitespace and (tries to) converts the rest of the input to integer (if no errors occur).
回答2:
So when I gave the input 4 was 3 present in the input buffer?
No, it wasn't.
scanf() reads (and consumes) from the standard input until a match the specified format (in your case an integer) is found. That format is converted and consumed as well.
来源:https://stackoverflow.com/questions/61641084/does-the-input-buffer-gets-cleared-after-scanf-reads