readf for the novice

Jesse Phillips jessekphillips+D at gmail.com
Tue Aug 17 10:10:22 PDT 2010


Ali Çehreli Wrote:

> 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;
> }
> 
> Ali

I created a similar function for my own use. I used a question answer style:

auto age = userInput!int("Please Enter you age");

It is meant only to work with stdin and allows for some very nice extension functionality. For example Yes/No questions are possible:

if(userInput!bool("Do you want to continue?")) { ... }

I then added some other functions:

auto outputFolder = pathLocation("Where you do want to place the output?");
auto color = menu!string("What color would you like to use?", ["Blue", "Green"]);

Using pathLocation will verify that the folder/file exists before returning (maybe creating the path could be an option). And menu will display the array with numbers for selection; the input accepted is a integer or string and will return an integer or string depending on the request (default int).

If any of these seem common enough I'd be willing to clean them up and try to make them Range friendly.

I also have a function that takes a bool delegate which will continually ask for input and validates the answer against the delegate before returning.


More information about the Digitalmars-d mailing list