Currently the only way I know how to do input in D is with the scanf() function. But god damn it's ugly. You would think that since it's an upgrade from C that they would have fixed that.
I'm looking for a way to do it with a single argument. Currently you have to do:
int foo = 0;
scanf("%i", &foo);
writeln("%i", foo);
But it would look a lot cleaner with a single argument. Something like:
int foo = 0;
scanf(foo);
writeln(foo);
Thanks.
readf("%d", &foo);
allows working with std.stdio.File
rather than C FILE*
foo = readln().strip().to!int();
int[] numbers = slurp!int("filename", "%d");
There's a really cool user-input module here:
https://github.com/Abscissa/scriptlike/blob/master/src/scriptlike/interact.d
Example code:
if (userInput!bool("Do you want to continue?"))
{
auto outputFolder = pathLocation("Where you do want to place the output?");
auto color = menu!string("What color would you like to use?", ["Blue", "Green"]);
}
auto num = require!(int, "a > 0 && a <= 10")("Enter a number from 1 to 10");
The above answers are great. I just want to add my 2 cents.
I often have the following simple function lying around:
T read(T)()
{
T obj;
readf(" %s", &obj);
return obj;
}
It's generic and pretty handy - it swallows any white space and reads any type you ask. You can use it like this:
auto number = read!int;
auto floating_number = read!float;
// etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With