示例代码:
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从它所提供的内容中获取并作用于它。
有人可以解释一下这种行为吗? 我正在运行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:~$
答案 0 :(得分:5)
问题是%d后的空格字符。这段代码工作正常:
import std.stdio;
int main()
{
int line = 0;
while (line != 1)
{
writef("Enter num 1: ");
readf(" %d", &line);
}
return 0;
}