readf在循环try-catch中没有正确分配

时间:2018-04-30 20:19:52

标签: d

如果' a'键入作为下面程序的输入,而不是整数,输出进入循环而不停止更多输入。为什么呢?

uint inputInt = 1;
while (inputInt > 0) {
  write("enter something: ");
  try {
    readf(" %s", inputInt);
    writefln("inputInt is: %s", inputInt);
  }
  catch (Exception ex) {
    writeln("does not compute, try again.");
    inputInt = 1;
  }
}

我希望inputInt能够被分配' 1'在catch块中,然后再次执行try块。但是,输出显示程序不会再次停止再次收集inputInt

enter something: does not compute, try again.
enter something: does not compute, try again.
enter something: does not compute, try again.
enter something: does not compute, try again.
enter something: does not compute, try again.
etc...

1 个答案:

答案 0 :(得分:1)

因为当readf失败时,它不会从缓冲区中删除输入。所以下一次循环它再次失败。

试试这个:

import std.stdio;
void main()
{
    uint inputInt = 1;
    while (inputInt > 0) {
        write("enter something: ");
        try {
            readf(" %s", inputInt);
            writefln("inputInt is: %s", inputInt);
        }
        catch (Exception ex) {
            readln(); // Discard current input buffer
            writeln("does not compute, try again.");
            inputInt = 1;
        }
    }
}