On 05/04/2012 06:18 AM, Iain wrote:
> I tried to use the sleep function from the Rosetta Code project:
> http://rosettacode.org/wiki/Sleep#D
>
> Am I right in thinking this is D1 code, as it will not compile under 2.059?
>
> So, I tried writing my own version, and hit my head against many brick
> walls along the way. My result takes more lines than C, C++ or C#, so
> I'm guessing it can't be the best solution.
>
> Could anyone explain how to optimise the code below before I post it to
> Rosetta?
>
> -----------------
> import std.stdio;
> import std.conv;
> import std.string;
> import core.thread;
>
> void main()
> {
> write("Enter a time to sleep (in seconds): ");
> string input = stdin.readln(); // have to make this a string first, it
> can't go directly into parse!
> auto time = parse!long(input); // have to use parse!, as to! crashes
> when it sees a \n
> writeln("Sleeping...");
> Thread.sleep( dur!("seconds")(time) );
> writeln("Awake!");
> }
>
>
> Many thanks!

You can use spaces in the format string to read and ignore all whitespace. This one ignores the '\n' and others that may have been left over from the previous read (I know that there can't be any in this small program):

import std.stdio;
import core.thread;

void main()
{
  write("Enter a time to sleep (in seconds): ");

  long time;
  readf(" %s", &time);

  writeln("Sleeping...");
  Thread.sleep( dur!("seconds")(time) );
  writeln("Awake!");
}

Some people have developed their own input modules. Reading any type can be as simple as in the following:

import std.stdio;
import core.thread;

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

void main()
{
  immutable time =
      read!long("Enter a time to sleep (in seconds): ");

  writeln("Sleeping...");
  Thread.sleep(dur!("seconds")(time));
  writeln("Awake!");
}

Ali

Reply via email to