Search code examples
d

readf not assigning properly within looped try-catch


If 'a' is typed as input for the program below, instead of an integer, the output goes into a loop without stopping for more input. Why?

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

I would expect inputInt to get assigned '1' in the catch block, and then the try block to be executed again. However, the output shows that the program does not stop to collect inputInt again a second time:

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...

Solution

  • Because when readf fails it doesn't remove the input from the buffer. So the next time round the loop it fails again.

    Try this:

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