stdin/stdout 的 D 命令行行为

D's command line behavior for stdin/stdout

示例代码:

import std.stdio;

int main()
{
    int line = 0;
    while (line != 1)
    {
        stdout.writef("Enter num 1: ");
        stdin.readf(" %d ", &line);
    }
    return 0; 
}

当此程序从命令行 运行 运行时,您希望只需输入数字 1,然后让程序退出。使用 D 编译器编译此程序时不会发生这种情况。我不确定为什么,除非它必须将 stdin 和 stdout 包含在单独的线程中,其中 stdin 将输入提供给 stdout 存储桶,然后在下一个输入中,stdout 从它提供的内容中获取并对其进行操作。

有人可以解释一下这种行为吗? 我是 运行ning dmd 版本 2.069.1

命令行输出:

sample@sample:~$ ./sample
Enter num 1: 1
x
sample@sample:~$

附加示例:

import std.stdio;

int main()
{
    int line = 0;
    while (line != 1)
    {
        stdout.writef("Wrong, echo %d, enter num 1: ", line);
        stdin.readf(" %d ", &line);
    }
    return 0; 
}

命令行:

sample@sample:~$ ./sample
Wrong, echo 0, enter num 1: 2
3
Wrong, echo 2, enter num 1: 4
Wrong, echo 3, enter num 1: 5
Wrong, echo 4, enter num 1: 6
Wrong, echo 5, enter num 1: 7
Wrong, echo 6, enter num 1: 8
Wrong, echo 7, enter num 1: 9
Wrong, echo 8, enter num 1: 1
Wrong, echo 9, enter num 1: 1
sample@sample:~$ 

您的问题是 %d 之后的 space 个字符。此代码工作正常:

import std.stdio;

int main()
{
    int line = 0;
    while (line != 1)
    {
        writef("Enter num 1: ");
        readf(" %d", &line);
    }
    return 0;
}