有关缓冲、getchar() 和 scanf() 的问题吗?
我正在学习C,并且有一些问题。请看一下下面的图片:
当阅读突出显示的文本时,我很困惑。是不是:当用户开始输入一些输入时,输入立即直接放入缓冲区中。当按下 Enter 键('\n')时,程序会从缓冲区读取并获取输入,然后清除缓冲区?
如果是,假设在程序中,我使用:scanf("%d", &a_variable)
,然后输入123astring,然后输入123 已从缓冲区中读取并清除。那么,缓冲区中现在包含“astring”?
我说得对吗?或者我误解了什么?
I am learning C and have some issues. Please, take a look at the picture below:
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 the buffer now contains "astring"?
Am I right? Or I am misunderstanding something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确实有两个缓冲区。
第一个是他们正在谈论的。它允许用户输入内容,然后删除等,而程序看不到任何内容。
第二个缓冲区将保存剩余的“astring”。
一个好方法是当按下 Enter 时第一个缓冲区传递到第二个缓冲区。第二个缓冲区由 scanf 读取。如果它是空的,程序就会等待。
第二个缓冲区几乎总是存在的。如果不是,您必须在用户键入时准确运行 scanf,即使在“无缓冲”情况下,这也是不正确的。
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.