D input: how-to (RFC)
Tyro[a.c.edwards]
nospam at home.com
Sun May 10 21:02:26 PDT 2009
I am looking for a D version of scanf() but I'm sure there is no such
thing so I tried contrived one. I am sure I missed a slew of obvious
things and that this cannot be used for much more than a little toy on
my personal computer. I would like to make it usable for others so I am
asking for some guidance/suggestions for making it better.
Thanks,
Andrew
This is written in D2 v2.029 with an updated std.random to fix a problem
I was having with the current release.
module ace.io;
private import std.conv: to, ConvError;
private import std.string: split, stripr;
public import std.stdio;
int read(/+File inFile = stdin,+/ A...)(out A a) /+Uncommenting results
in: Error: arithmetic/string type expected for value-parameter, not
File+/
{ start:
auto data = stripr(readln());
auto input = split(data);
string assign()
{
return
` try {
if(a.length != input.length)
return -1;
a[i] = to!(typeof(t))(input[i]);
} catch (ConvError e) {
writeln("Invalid input!");
goto start;
}`;
}
foreach(i, t; a)
{
static if(is(typeof(t) == void))
{}
else static if(is(typeof(t) == bool))
{}
else static if(is(typeof(t) == byte))
mixin(assign);
else static if(is(typeof(t) == ubyte))
mixin(assign);
else static if(is(typeof(t) == short))
mixin(assign);
else static if(is(typeof(t) == ushort))
mixin(assign);
else static if(is(typeof(t) == int))
mixin(assign);
else static if(is(typeof(t) == uint))
mixin(assign);
else static if(is(typeof(t) == long))
mixin(assign);
else static if(is(typeof(t) == ulong))
mixin(assign);
/+static if(is(typeof(t) == cent))
mixin(assign);
static if(is(typeof(t) == ucent))
mixin(assign);+/
else static if(is(typeof(t) == float))
mixin(assign);
else static if(is(typeof(t) == double))
mixin(assign);
else static if(is(typeof(t) == real))
mixin(assign);
else static if(is(typeof(t) == ifloat))
a[i] = ifloat.max;
else static if(is(typeof(t) == idouble))
a[i] = idouble.max;
else static if(is(typeof(t) == ireal))
a[i] = ireal.max;
else static if(is(typeof(t) == cfloat))
a[i] = cfloat.max;
else static if(is(typeof(t) == cdouble))
a[i] = cdouble.max;
else static if(is(typeof(t) == creal))
a[i] = creal.max;
else static if(is(typeof(t) == char))
a[i] = input[i][0];
else static if(is(typeof(t) == wchar))
mixin(assign);
else static if(is(typeof(t) == dchar))
a[i] = input[i][0];
else static if(is(typeof(t) == string))
if(a.length > 1)
a[i] = input[i];
else
a[i] = data;
else static if(is(typeof(t) == dstring))
{}
else static if(is(typeof(t) == char[]))
a[i] = stripr(data).dup;
}
return 0;
}
More information about the Digitalmars-d-learn
mailing list