readf for the novice

Ali Çehreli acehreli at yahoo.com
Mon Aug 16 13:54:09 PDT 2010


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?


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++.)


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();

Ignoring stripping whitespace, read can be implemented like this:

T read(T)()
{
     T value;
     readf("%s", &value);
     return value;
}

Actually stream.readf's signature was also nice. Can we do the same with 
stdio.readf?

   readf(&v0, &v1, &v2);

Ali


More information about the Digitalmars-d mailing list