Comment #0 by bearophile_hugs — 2010-08-22T20:02:39Z
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.
Comment #1 by bearophile_hugs — 2010-08-23T05:14:22Z
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, "<");
}
Comment #2 by bearophile_hugs — 2011-02-08T13:13:01Z
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);
Comment #3 by bearophile_hugs — 2011-10-28T18:22:54Z
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().
Comment #4 by lt.infiltrator — 2014-03-19T21:32:57Z