Does the input buffer gets cleared after scanf reads?

橙三吉。 提交于 2020-06-29 05:04:41

问题


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

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