User Input: Ask for a number
● Beginner3 min
term.prompt_int asks for a whole number, and asks again until it gets one.
use std.term
fn main() {
const age = term.prompt_int("Your age?") ?? 0
print("Next year you will be {age + 1}")
}The program ran and printed:
kavach run number.kav
Your age? Please type a whole number.Your age? Next year you will be 32
Typed by the user: thirty, then 31. What is typed isn't part of the program's output, so it doesn't show in the box.
"thirty" isn't a number, so prompt_int says so and asks again. You never have to turn the text into a number yourself, or deal with an answer that isn't one. term.prompt_float does the same for numbers like 2.5.
What Kavach does for you
Asking for a number asks until it gets one
term.prompt_intanswers "thirty" withPlease type a whole number.and asks again, so your code only ever sees a number.