readf for the novice

Sean Kelly sean at invisibleduck.org
Mon Aug 16 14:01:34 PDT 2010


Ali Çehreli Wrote:

> Since cstream is deprecated and stdio.readf is finally available with 
> 2.048, I started modifying my D book by replacing code like
> 
>      T var;
>      din.readf(&var);
> 
> with
> 
>      T var;
>      readf("%s", &var);
> 
> 
> 1) I couldn't go far, because stdio.readf does not ignore whitespace and 
> code like the following fail:
> 
>      int i;
>      int j;
> 
>      readf("%s", &i);
>      readf("%s", &j);
> 
> When the input is
> 
> 42 43
> 
> the output is
> 
> std.conv.ConvError: std.conv(1070): Can't convert value 
> `LockingTextReader(File(807637C),  )' of type LockingTextReader to type int
> [...]
> 
> Is that by design? Should the users strip the input themselves?

It looks like a bug to me.

> 2) This is not a show stopper, but having to provide a format string for 
> simple value input is unnecessary. It makes D less suitable for 
> programming novices. (I see D very easy for novices in general, 
> especially compared to C and C++.)

Since D has TypeInfo for variadic arguments, you're right that a format string shouldn't often be necessary.

> 3) We need a simple way of reading values from stdin if only for the novice.
> 
> Another solution is using string.strip and conv.parse:
> 
>      auto line = strip(stdin.readln());
>      auto i = parse!int(line);
>      auto d = parse!double(line);
> 
> but that requires importing std.string and std.conv in addition to 
> std.stdio. Also, with that, both of the values must be on the same line.
> 
> A novice should be able to read as simple as
> 
>      auto d = read!double();
>      auto i = read!int();

Seems like a good idea to me.


More information about the Digitalmars-d mailing list