我今天刚刚在 C 班进行了一次测试,我有理由相信答案可能是错误的。
scanf("%d\n", &x); // Evaluate the expression for the string "54321\n"
这个想法非常简单。找到一个整数,并将扫描到的数放到整型变量对应的内存位置x
。但是,我不相信这个电话scanf
将永远终止。
就我而言,所有的电话scanf
标准 I/O 通过按 Enter 键终止,因此无需在说明符字符串中包含换行符。事实上,这种冗余只会导致程序在搜索永远不会与字符串匹配的内容时停止。
有没有人可以澄清一下技术细节scanf
函数可以解决这个问题吗?
我不相信对 scanf 的调用会终止。
6个字符输入如"54321\n"
不足以造成这种情况scanf("%d\n", &x);
回来。程序停滞。还必须发生其他事情。
'\n'
指挥scanf()
消耗空白并这样做直到
检测到非空白。
stdin
关闭了
输入错误发生在stdin
(rare).
As stdin
通常是line缓冲的,scanf()
以块的形式接收数据。
The first chunk 123Enter is not enough to cause scanf("%d\n", &x);
to return. One of the 3 above needs to happen.
Any following input with some non-white-space fulfills #1, be it:
456Enter or
xyzEnter or
EnterEnter$Enter or ...
Then scanf()
will return with a 1 indicate a value, 123, was stored in x
. The 4, x or $ above was the non-white-space detected that caused completion. That character will be the next character read by subsequent input on stdin
.
scanf("%d\n", &x);
几乎可以肯定是使用了错误的代码,因为它有义务another用户输入的行,并且不检查其返回值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)