Input
input asks a question and reads the answer into a variable:
string name
int age
input("name: ", name)
input("hi {name}, how old are you? ", age)
print("{name} is {age}")
name: Noa
hi Noa, how old are you? sixteen
please enter a whole number from -2147483648 to 2147483647
hi Noa, how old are you? 16
Noa is 16
The variable's type decides what counts as an answer. A wrong answer is asked again; the program never crashes on it.
| type | accepts |
|---|---|
string | the whole line |
int, byte, ... | a whole number that fits the type, spaces around it are fine |
char | exactly one letter |
bool | yes no y n true false 1 0, in any case |
The question is optional: input(age) just reads.
End of input
input gives back true when it read an answer. At the end of the input (Ctrl+D on Linux, Ctrl+Z then Enter on Windows, or the end of a file or pipe) it gives back false and leaves the variable as it was:
string line
while input(line) {
print("got: {line}")
}
print("done")
After the end, every later input gives back false too, so a loop like this one always stops.
Safe by design
- There is no buffer size: a line of any length is read.
- The whole line is read, so no newline is left over for the next
input. - Windows line endings (
\r\n) are handled. - The typed text is only ever data.
{name}or%sin an answer is just text. - The question always appears before the program waits, even when output goes through a pipe.
- On the Windows console, Hebrew and other non-English text is read and shown correctly.
Passwords
input.secret works the same way, but hides what's typed:
string password
input.secret("password: ", password)
login(password)
password.destroy()
The terminal shows its typing again afterwards, even if the user presses Ctrl+C while it's hidden. destroy then wipes the password from memory.