If not already present, a function template similar to this one may be useful for the std.stdio module. Similar functions are present in Basic and Python languages: T input(T)(string msg) { write(msg); auto read = readln(); static if (!is(T == string) && !is(T == dstring) &&!is(T == wstring)) read = read.strip(); return to!T(read); } To be used mostly in scripts, as: double x = input!double("Enter value x: "); Its name may be changed if there is collision with something different, but it needs to be simple, given its purpose. This function may be made much more refined, but I suggest to keep it simple. Even the static if it contains is more complex than originally thought.
Improved code. Both IsType() and IsString() may be useful to add to std.traits, if something similar is not already present. import std.string: chomp; import std.stdio: write, readln; import std.conv: to; // true is T is one of the successive types template IsType(T, Types...) { static if (Types.length) enum bool IsType = is(T == Types[0]) || IsType!(T, Types[1..$]); else enum bool IsType = true; } // true if T is string, wstring, or dstring template IsString(T) { enum bool IsString = IsType!(T, string, wstring, dstring); } T input(T)(string msg) { write(msg); auto read = readln(); static if (IsString!T) return to!T(read.chomp()); else return to!T(read.strip()); } // usage demo -------------- import std.stdio: writeln; void main() { //auto x = input!string("Enter value x: "); auto x = input!double("Enter value x: "); writeln(">", x, "<"); }
Adam Ruppe has suggested: > I'd say make it do a combination of writef though, so you can do more > complex prompts. > > auto number = ask!int("Enter a number, %s", name);
A D2 program that reads a string from the keyboard: import std.stdio; void main() { string s = readln(); writeln(">", s, "<"); } Running it it shows that the newline is left inside the string s: ...>test 123 >123 < I don't know other languages where the command line input function leaves the newline at the end of the input string. This is why in input() I have used chomp().
Would you like to make a PR for this?