Let's mimic Python's input() function.
(1) input()
|
def main():
name = input("Name: ") # no extra newline char.
print(f"Hello {name}!")
|
import std.stdio;
import std.string; // readln(), chomp()
string input(const string msg = "")
{
write(msg);
// chomp() removes the trailing newline
return readln().chomp();
}
void main()
{
string name = input("Name: ");
writefln("Hello %s!", name);
}
|
Output:
If you call input() in an infinite loop and the user presses Ctrl+D, you can get stuck in an infinite loop where only a Ctrl+C would help. Here is how to notice if the user pressed Ctrl+D:
| (2) notice Ctrl+D
|
import std.stdio;
import std.string; // readln(), chomp()
class EOFException : Exception
{
this(string msg = "")
{
super(msg);
}
}
string input(const string msg = "")
{
write(msg);
auto line = readln();
if (line is null) // if Ctrl+D was pressed
{
throw new EOFException();
}
return line.chomp();
}
|