特殊的writef/writefln行为?

Cor*_*urn 3 d

所以我一直在看D大约15分钟,所以难怪我有疑问,但是有些奇怪的事情发生在我身上.

我从安装d 这里和Visual d从这里,我跑在Visual Studio 2010专业版的一切.D示例编译并运行,调试器似乎工作正常.

在浏览dsource.org的基础教程时,我正在阅读Wait部分,当我注意到如果你使用writef而不是writefln那么输出的最后一行在暂停打印.

这是示例的代码:

import std.c.stdio; /* for getch() */
import std.process; /* for system() */
import std.stdio; /* for writefln */

void main() { 
    writefln("Press a key (using 'std.c.stdio.getch();' to wait) . . .");
    getch();

    writefln("Waiting again\n(using 'system(\"pause\");'):");
    system("pause");
}
Run Code Online (Sandbox Code Playgroud)

这里是我的,注意,唯一的变化是writefln,以writef

import std.c.stdio; /* for getch() */
import std.process; /* for system() */
import std.stdio; /* for writefln */

void main() { 
    writef("Press a key (using 'std.c.stdio.getch();' to wait) . . .");
    getch();

    writef("Waiting again\n(using 'system(\"pause\");'):");
    system("pause");
}
Run Code Online (Sandbox Code Playgroud)

随着writef程序将显示在屏幕上什么都没有,在暂停getch,然后当我按一个键我看到提示:

Press a key (using 'std.c.stdio.getch();' to wait) . . .Waiting again
Press any key to continue . . . 
Run Code Online (Sandbox Code Playgroud)

但不是"(使用'系统("暂停");'):".在我按下一个键以通过控制台中的"pause"命令后,会出现括号语句.如果我使用writefln它打印,等待,打印两行,然后再按照你的期望再次等待.

什么解释了这种行为?

And*_*vić 6

stdout.flush();在拨打write或之后使用writef.后面这些调用不会刷新缓冲区,这就是你看到这种行为的原因.Btw getch不在std.c.stdio(至少不在D2?),它在DMC的CRT库(SNN.lib)中,要正确使用它,你必须将它原型化为extern (C) int getch();:

extern (C) int getch();
import std.process; /* for system() */
import std.stdio; /* for writefln */

void main() { 
    writef("Press a key (using 'std.c.stdio.getch();' to wait) . . .");
    stdout.flush();
    getch();

    writef("Waiting again\n(using 'system(\"pause\");'):");
    stdout.flush();
    system("pause");
}
Run Code Online (Sandbox Code Playgroud)

但这不是跨平台兼容的原因getch().如果您想使用更好的用户输入工具,可以查看Jesse的cmdln库:https://github.com/he-the-great/JPDLibs/tree/cmdln.它有一个相当酷的界面:

auto num = require!(int, "a > 0 && a <= 10")("Enter a number from 1 to 10");
Run Code Online (Sandbox Code Playgroud)