On Friday, 17 March 2017 at 00:35:32 UTC, Philip Miess wrote:
This is my first 100+ line D program.
https://gitlab.com/pmiess/101gamesDlangComputerGames/blob/master/
aceyducy.d
Its a translation/refactor of aceyducy from 101 basic programs.
Could someone look over it and see if I've made any glaring mistakes.
Suggestions are welcome also.

Thanks,
Phil

Hello Phil,

I think there might be an issue with this function here:
int inputInt ( string prompt){
  int val ;
  writeln( prompt ~ "? ");
  string line;
  bool found = false;
  while ( !found ) {
    try {
      readf(" %d", &val);
      readln();
      found = true;
    } catch (Exception e) {
      writeln( "? " );
    }
  }
  return val;
}

I get an infinate loop if I put in something that's not convertible to an integer. I think what happens is that you catch the exception, the input still remains (presumably the buffer/range it's reading from hasn't had the chance to iterate through because of the thrown exception), and readf will always try and convert the input again.

I'd probably rewrite it as this:

int inputInt ( string prompt ){
  import std.range : popBack;
  writeln( prompt ~ "? ");

  string line;
  while ((line = readln) !is null){
    line.popBack; // remove line terminator
    try {
        return line.to!int;
    } catch (Exception e) {
        writeln ("? ");
    }
  }
  assert(0);
}

Thanks,
Jordan

Reply via email to