开发者

Question about buffering, getchar() and scanf()?

I am learning C and have some issues. Please, take a look at the picture below:

Question about buffering, getchar() and scanf()?

When reading the highlight text, I am quite confused. Is it that: when the user starts entering some inputs, the input is put directly and immediately in the buffer. And when Enter key is hit ('\n'), the program reads and gets input from the buffer and then clear the buffer?

If it is, suppose in the program, I use: scanf("%d", &a_variable) and then I enter 123astring, then 123 is read and clear from the buffer.So, In th开发者_JAVA技巧e buffer now contains "astring"?

Am I right? Or I am misunderstanding something?


There really are two buffers. The first is the one they are talking about. It allows the user to type in stuff, then delete, etc. without the program ever seeing any of it. The second buffer is what would be holding the remaining "astring".

A good way to think of it is the first buffer passes to the second buffer when Enter is pressed. The second buffer is read by scanf. And if it is empty, the program waits.

The second buffer is pretty much always there. If it wasn't, you would have to be running scanf exactly when the user typed which is not true even in the 'unbuffered' case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜