Skip to content
Kavachकवच

User Input

Also known as: input read line stdin prompt ask scanf cin readline keyboard password

● Beginner4 minBefore this: Output, VariablesSpec 14.13

term.prompt(question) prints a question and gives back the line the user types.

Asking the user lives in the std.term module, so a program that asks starts with use std.term.

use std.term

fn main() {
    const name = term.prompt("Your name?") ?? "friend"
    print("Hello, {name}")
}

The program ran and printed:

kavach run text.kav

Your name? Hello, Asha
text.kav: Kavach code, then what running it prints

Typed by the user: Asha. What is typed isn't part of the program's output, so it doesn't show in the box.

Why the ?? "friend"

The user may type nothing at all and end the input (Ctrl+D, or a file that runs out). Then there is no answer, and term.prompt gives none. ?? "friend" says what to use instead, so name is always text.

The program can't forget that case: using the answer without saying what to do when it is missing is a compile error.

One page for each form

Try it yourself

Ask for the user's city and print "Welcome to <city>", with "your city" when nothing is typed.
Show the answer

const city = term.prompt("Your city?") ?? "your city", then print("Welcome to {city}").