Sub topic 8
Asking Again Until the Input Is Valid
What this chapter assumes
You know how to call read_line, trim its result, and parse it into a number. You also know how to flush stdout after print!. This chapter combines those pieces in a loop, so a typo doesn't end the program.
Why a loop is needed
parse::<u32>() returns an Err when the text is not a number. Up to now, programs reported that error and exited. For an interactive program, the better response is to explain the problem and ask again. That takes a loop with two exits: a valid value, or the end of input.
A basic retry loop
This program keeps asking until you press Ctrl-D (Ctrl-Z then Enter on Windows). Invalid text prints a message and the loop continues.
use std::io::{self, Write};
fn main() -> io::Result<()> {
let stdin = io::stdin();
loop {
print!("Enter a number (Ctrl-D to quit): ");
io::stdout().flush()?;
let mut line = String::new();
if stdin.read_line(&mut line)? == 0 {
println!();
break;
}
match line.trim().parse::<f64>() {
Ok(n) => println!("{n} squared is {}", n * n),
Err(_) => println!("Please enter a number."),
}
}
Ok(())
}Three details matter here:
String::new()is inside the loop.read_lineappends to the string, so reusing one string would glue each new line onto the old text.- The
Ok(0)check comes before parsing. At end of input,read_linereturnsOk(0)and leaves the string empty. An empty string fails to parse, so without this check the program would print "Please enter a number." forever. flushruns on every pass, so the prompt reappears each time.
Returning the value from a function
Most programs want a value, not a loop that runs the whole program. Put the loop in a function and return as soon as the input is acceptable. The return type is io::Result<Option<u32>>. The io::Result carries real read failures, and None means the input ended before a valid answer arrived.
This version also rejects values that parse but make no sense, using a match guard.
use std::io::{self, Write};
fn ask_age() -> io::Result<Option<u32>> {
let stdin = io::stdin();
loop {
print!("Enter your age (0-130): ");
io::stdout().flush()?;
let mut line = String::new();
if stdin.read_line(&mut line)? == 0 {
return Ok(None);
}
match line.trim().parse::<u32>() {
Ok(age) if age <= 130 => return Ok(Some(age)),
Ok(_) => println!("That age is out of range."),
Err(e) => println!("Not a valid number: {e}"),
}
}
}
fn main() -> io::Result<()> {
match ask_age()? {
Some(age) => println!("Next year you will be {}.", age + 1),
None => println!("\nNo input given."),
}
Ok(())
}The caller decides what end of input means. Here main prints a message. Another program might use a default value.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| No `Ok(0)` check | Endless loop of error messages when input is piped or closed | Test the byte count right after `read_line` |
| Reusing one `String` across passes | Parsing fails after the first bad line, since old text remains | Create the string inside the loop, or call `clear()` |
| Using `?` on the parse result inside the loop | The first typo ends the function | `match` on the parse result and handle `Err` yourself |
| Forgetting `flush` | The prompt appears late or not at all | Call `io::stdout().flush()?` before reading |
Exercise
In ask_age, what happens if you move let mut line = String::new(); above the loop and the user types abc, then 42?
Show answer
The first read_line stores "abc\n" and parsing fails. The second read_line appends, so the string holds "abc\n42\n". After trimming, the text is "abc\n42", which still fails to parse. The loop never accepts a valid value. Creating the string inside the loop, or calling line.clear() at the start of each pass, fixes it.