Input handling? (newbie alert!)

Jonathan M Davis jmdavisprog at gmail.com
Thu Sep 9 18:07:43 PDT 2010


On Thursday 09 September 2010 17:48:47 Bernard Helyer wrote:
> I've not time for a more full answer now (I'll try later), but please,
> for the love of God, don't use scanf! As a general hint, use
> std.stdio.readln to get input as a string, then use the `to` function
> found in std.conv to convert it into what you want:
> 
>    auto input = readln();
>    auto asInteger = to!int(input);
> 
> To handle errors, you'll probably want to catch whatever it is that to
> throws on failure:
> 
>    int i;
>    auto input = readln();
>    try {
>        i = to!int(input);
>    } catch (TheThingThatToThrows) {
>        i = 0;
>    }
> 
> I don't know how to!int handles entry of floating point numbers, if it
> doesn't, what you may want to do:
> 
>     int i;
>     auto input = readln();
>     try {
>         i = cast(int) to!double(input);
>     } catch (TheThingThatToThrows) {
>         i = 0;
>     }
> 
> ---
> 
> Sorry I couldn't be more thorough. I hope that helps!

Yes std.stdio.readln() would be a much better way to go. However, I'd suggest 
using std.conv.parse() rather than std.conv.to(). It's less picky about 
whitespace, and it allows you to deal with the case where you have multiple 
values on the same line. For string manipulation functions, check out the 
functions in std.string.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list