Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a less ugly way to do input in D than scanf()?

Tags:

input

scanf

d

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.

like image 313
Skiddzie Avatar asked Feb 04 '14 21:02

Skiddzie


3 Answers

  • readf("%d", &foo); allows working with std.stdio.File rather than C FILE*
  • foo = readln().strip().to!int();
  • For reading entire files with lines formatted in the same way:
    int[] numbers = slurp!int("filename", "%d");
like image 138
Vladimir Panteleev Avatar answered Nov 13 '22 08:11

Vladimir Panteleev


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");
like image 37
Andrej Mitrović Avatar answered Nov 13 '22 07:11

Andrej Mitrović


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.
like image 4
Sergei Nosov Avatar answered Nov 13 '22 07:11

Sergei Nosov