d - 为什么 readf 没有按预期运行?

标签 d dmd

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[] for­mat, A args);

   For­mat­ted 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/

相关文章:

d - 为什么有些功能需要 GC?

enums - 编译器认为枚举值从 129 开始

编译时无法读取结构体枚举

d - 如何在没有 D 运行时编译 D 应用程序?

multidimensional-array - D - 为多维静态数组的结构成员设置默认值

d - 如何从 D 中的纯函数获取详细的错误消息?

sockets - 允许 D 应用程序和浏览器之间双向通信的工具链

dll - 如何在 Windows 的 D 语言程序中使用 SQLite 库?

multithreading - 编译器优化破坏多线程代码

windows-7 - 如何在Win7和dmd(D2)中使用gtkD?