first try
Philip Miess via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Mar 18 05:27:14 PDT 2017
On Fri, 17 Mar 2017 03:55:26 +0000, Jordan Wilson wrote:
> Hello Phil,
>
> I think there might be an issue with this function here:
snip
> 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
Jordan,
I don't see an infinite loop, but I do see one failure and prompt
printed for each character on the line that doesn't parse.
I added a readline to the catch so that the input should be emptied when
the parse fails. Does that fix your infinite loop?
I tried your proposed fix and it works the same as adding the readline
for me.
Thanks for taking the time to help,
Phil
More information about the Digitalmars-d-learn
mailing list