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

readf not assigning properly within looped try-catch

如果输入 '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;
  }
}

我希望 inputIntcatch 块中被分配为“1”,然后再次执行 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...

因为当 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;
        }
    }
}