import std.stdio;
void main(){
int n;
while(readf("%d", &n)){
if(n == 11)
break;
writeln(n);
}
}
第一次迭代有效,它打印 n
,但在那之后 readf()
永远不会回来。该文档只有一行解释
readf()
:uint readf(A...)(in char[] format, A args);
Formatted read one line from stdin.
我做错了什么吗?或者
readf()
有什么问题吗? ?我只需要从标准输入中读取数字。使用:DMD 2.054 64 位
最佳答案
我相信这是因为readf
处理空格的方式不同于 scanf
在 C 中。您需要显式读取空格,因此更改 readf("%d", &n)
至 readf("%d ", &n)
它应该可以工作(希望如此)。
这是实现该功能的 Andrei 的引述:
This is by design. The example works when modified as follows:
import std.stdio;
void main() {
int i, j;
readf("%s", &i);
readf(" %s", &j);
}The space before the second parameter tells readf to read and skip all whitespace before attempting conversion.
I've implemented readf to be a fair amount more Nazi about whitespace than scanf in an attempt to improve its precision. Scanf has been famously difficult to use for complex input parsing and validation, and I attribute some of that to its laissez-faire attitude toward whitespace. I'd be glad to relax some of readf's insistence on precise whitespace handling if there's enough evidence that that serves most of our users. I personally believe that the current behavior (strict by default, easy to relax) is best.
http://www.digitalmars.com/d/archives/digitalmars/D/bugs/Issue_4656_New_stdio.readf_does_not_ignore_white_space_24214.html
关于d - 为什么 readf 没有按预期运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7118734/