fgets 指令被跳过。为什么?
每当我在 fgets 之前执行 scanf 时, fgets 指令就会被跳过。我在 C++ 中遇到过这个问题,我记得我必须有一些指令来清除标准输入缓冲区或类似的东西。我想 C 也有一个等价的东西。它是什么?
谢谢。
Whenever I do a scanf before a fgets the fgets instruction gets skipped. I have come accross this issue in C++ and I remember I had to had some instrcution that would clear the stdin buffer or something like that. I suppose there's an equivalent for C. What is it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我敢打赌这是因为 \n 卡在输入流中。
请参阅以下问题之一:
我无法刷新标准输入。
我该如何在此处刷新 STDIN?
scanf() 导致无限循环
或 这个答案。
另外:为什么不使用 scanf()。
PS
fgets()
是一个函数,而不是一条指令。I'll bet it's because of the \n stuck in the input stream.
See one of these questions:
I am not able to flush stdin.
How do I go about Flushing STDIN here?
scanf() causing infinite loop
or this answer.
Also: Why not to use scanf().
P.S.
fgets()
is a function, not an instruction.调用
scanf()
之后的fgets()
函数可能1不会被跳过。 可能1在输入流中发现换行符后立即返回。在
fgets()
之前调用scanf()
几乎总是会导致scanf()
留下未使用的换行符 ('\n') 在输入流中,这正是 fgets() 正在寻找的。
为了混合
scanf()
和fgets()
,您需要从调用scanf()
中删除留下的换行符输入流。刷新标准输入(包括换行符)的一种解决方案将类似于以下内容:
1 - 在没有看到实际代码的情况下很难确定。
或者,如 Jerry Coffin 在下面的评论中建议,您可以使用
scanf("%*[^\n]");
。"%*[^\n]"
指令指示scanf()
匹配非换行符并禁止分配转换结果。来自http://c-faq.com/stdio/gets_flush1.html:
或者,正如 Chris Dodd 在下面的评论中建议的那样,您可以使用
scanf("%*[^ \n]%*1[\n]");
。"%*[^\n]%*1[\n]"
指令指示scanf()
匹配非换行符,然后匹配一个换行符并抑制转换结果的赋值。The
fgets()
function following the call toscanf()
is probably1 not getting skipped. It is probably1 returning immediately having found a newline in the input stream.Calling
scanf()
beforefgets()
almost always results inscanf()
leaving an unused newline ('\n'
) in the input stream, which is exactly whatfgets()
is looking out for.In order to mix
scanf()
andfgets()
, you need to remove the newline left behind by the call toscanf()
from the input stream.One solution for flushing stdin (including the newline) would be something along the lines of the following:
1 - It is difficult to be certain without seeing the actual code.
Or, as Jerry Coffin suggested in his comment below, you could use
scanf("%*[^\n]");
. The"%*[^\n]"
directive instructsscanf()
to match things that are not newlines and suppress assignment of the result of the conversion.From http://c-faq.com/stdio/gets_flush1.html:
Or, as Chris Dodd suggested in his comment below, you could use
scanf("%*[^\n]%*1[\n]");
. The"%*[^\n]%*1[\n]"
directive instructsscanf()
to match things that are not newlines and then match one newline and suppress assignment of the results of the conversion.您可以将此行放在
fgets()
调用之前,这样就会在您按enter
时生成尾随'\n'
You can just put this line before your
fgets()
call and that'll get the trailing'\n'
generated when you pressedenter