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

readf未在循环try-catch中正确分配,d,D,如果在下面的程序中键入“a”作为输入,而不是整数,则输出将进入循环,而不会停止以获取更多输入。为什么? uint inputInt = 1; while (inputInt > 0) { write("enter something: "); try { readf(" %s", inputInt); writefln("inputInt is: %s", inputInt); } catch (Exception ex) { writeln("do

如果在下面的程序中键入“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
catch
块中被分配“1”,然后
try
块将再次执行。但是,输出显示程序不会再次停止收集
输入

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;
        }
    }
}