Equivalent of scanf

Jonathan M Davis jmdavisprog at gmail.com
Sun Jul 18 03:18:18 PDT 2010


On Sunday 18 July 2010 02:58:59 Michael Koehmstedt wrote:
> I am doing this and it is throwing an exception.
> 
> string d = readln( );
> int i = to!int( d );
> 
> I tried
> 
> string d = "50";
> int i = to!int( d );
> 
> and that worked ok.

That would be because readln() was likely giving you more than just an int. All 
it would take would be a character of whitespace or a newline (there's a decent 
chance that readln() returns a string that ends in a newline) and to!int() would 
throw. So, if you're dealing with strings which may include stuff other than what 
you're actually trying to convert to, then parse!T() would likely be a better 
choice. You can also use std.string.strip() on a string to get rid of any 
whitespace on its ends if you're sure that it's only a number with whitespace.

If you really feel that we should have a version of scanf() for D, then you can 
always open up a bug report with enhancement request as the severity. If one 
isn't in the works, it might encourage it, and if one is already in the works, 
it might make it happen faster (since there would be an obvious desire for it 
plus there would be a bug report as a reminder).

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list