Elixir User Input
User input is text typed at the keyboard while a program runs. IO.gets reads one typed line and returns it as a string.
Trimmed input greets by name
The typed input for this block is Ana. The prompt and the greeting share one line because the prompt adds no newline.
name = IO.gets("Name? ") |> String.trim()
IO.puts("Hello, #{name}")Two prompts read two lines
The typed inputs for this block are Ana and then Lee. Each IO.gets call reads one line.
first = IO.gets("First name? ") |> String.trim()
last = IO.gets("Last name? ") |> String.trim()
IO.puts("Full name: #{first} #{last}")Typed text parses into a number
The typed input for this block is 30. Integer.parse turns the trimmed text into a number the code can add to.
age_text = IO.gets("Age? ") |> String.trim()
{age, ""} = Integer.parse(age_text)
IO.puts("Next year: #{age + 1}")Example
name = IO.gets("Name? ") |> String.trim()
number_text = IO.gets("Number? ") |> String.trim()
{number, ""} = Integer.parse(number_text)
IO.puts("#{name}, double is #{number * 2}")Key points
- IO.gets: it prints a prompt and waits for one line of typed text.
- Return value: IO.gets returns the typed line together with its trailing newline.
- String.trim: it removes the newline and other blank space from both ends of a string.
- Prompt: the prompt text prints with no newline after it, so later output continues on the same line.
- Cleanup: pass the raw line through String.trim before using the text.
- Numbers: typed input stays text until a parse function turns it into a number.
In this example, the typed inputs are Bo and 7, and both prompts appear on the output line before the answer. The name is trimmed, the number text is trimmed and parsed, and the last line prints the name with the number doubled.
Note
the typed line ends when the reader presses Enter.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does this lesson pass the IO.gets result through String.trim?