| intermediate read from stdin
|
import readline
def main():
name = input("Name: ").strip()
print(f"Hello {name}!")
|
import std/strutils # strip, split, join
import std/strformat # &"Hello {name}!"
import std/rdstdin # for inputExtra()
# simple solution
proc input(prompt: string = ""): string =
stdout.write(prompt)
stdin.readLine()
# intermediate solution
proc inputExtra(prompt: string = ""): string =
## Like Python's ``input()`` function. Arrows also work.
##
## You can also specify a prompt.
## The extra thing is that the arrows also work, like in Bash.
## In Python you can have the same effect if you ``import readline``.
## If the user presses Ctrl+C or Ctrl+D, an EOFError exception is raised
## that you catch on the caller side.
##
## .. code-block:: nim
##
## try:
## let name = inputExtra("Name: ")
## except EOFError:
## echo "user abort" # Ctrl+C or Ctrl+D was pressed
var line: string = ""
let val = readLineFromStdin(prompt, line) # line is modified
if not val:
raise newException(EOFError, "abort")
line
proc main() =
let name = inputExtra("Name: ").strip
echo &"Hello {name}!"
|
In Python it's enough to import readline and special keys (left/right arrows, HOME, END, etc.) will magically work.
In Nim you can achieve the same with some extra work. But if you hide it in a procedure, you can keep it simple.
Problem
This solution is not perfect. If you want to make a colored prompt and/or if you type in a Unicode text, then you may experience some glitches. In the next post we'll see an even better solution.