Sub topic 8
Asking again until the input is valid
This chapter assumes you can already call read_line, trim its result, and call parse on the text. You should also be comfortable with match, loop, and the ? operator in a function that returns io::Result. Here you combine those pieces into a loop that keeps asking until the user gives a usable answer, and that stops cleanly when no more input will ever arrive.
Why one attempt is not enough
The age program from the previous chapter reads one line, parses it, and exits. If the user types abc, the program prints an error and ends. That is fine for a demo, but most interactive programs should let the user fix the mistake.
Input can fail in three different ways, and a retry loop has to treat each one differently:
| What happened | Example | What the loop should do |
|---|---|---|
| The line was read but does not parse | `abc`, `-3` for a `u32`, an empty line | Print a message and ask again |
| The line parsed but is not acceptable | `500` when ages must be 1 to 120 | Print a message and ask again |
| Input ended | `read_line` returned `Ok(0)` | Stop asking, because no new answer can arrive |
| The read itself failed | `Err(io::Error)` | Stop and report the error with `?` |
The first two are problems with the user's text, so asking again can help. The last two are problems with the input stream, so asking again cannot help.
The basic retry loop
Wrap the prompt, read, and parse steps in loop. Leave the loop only when you have a good value or when input has ended.
use std::io::{self, Write};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let age: u32 = loop {
print!("Enter your age: ");
io::stdout().flush()?;
let mut line = String::new();
if stdin.read_line(&mut line)? == 0 {
println!();
println!("No input received. Giving up.");
return Ok(());
}
match line.trim().parse::<u32>() {
Ok(n) => break n,
Err(e) => println!("Not a valid number ({e}). Try again."),
}
};
println!("Next year you will be {}.", age + 1);
Ok(())
}Several details here matter.
loopis an expression.break nmakes the whole loop evaluate ton, soageis assigned directly and does not need to be declaredmutahead of time.- The prompt is printed with
print!, which does not end in a newline. Without theflush, the prompt may not appear before the program blocks on the read. - The
Err(e)arm does not use?. A parse failure is expected user behavior, so the program reports it and continues. Only theio::Errorfromread_lineandflushis propagated with?. return Ok(())inside the loop endsmainearly. That is the right choice when input has ended and there is no value to continue with.
Create the String inside the loop
read_line appends to the string you give it. It does not replace the contents. In the loop above, let mut line = String::new(); runs on every iteration, so each attempt starts empty.
If you declare the String outside the loop and forget to clear it, the second attempt contains the first attempt's text plus the new text. A failed abc followed by 42 would be read as abc\n42\n, which never parses.
use std::io;
fn main() -> io::Result<()> {
let stdin = io::stdin();
let mut line = String::new(); // declared once, outside the loop
loop {
line.clear(); // required: read_line appends
if stdin.read_line(&mut line)? == 0 {
break;
}
println!("got {:?}", line.trim());
}
Ok(())
}Reusing one String avoids an allocation per line, but it needs the explicit clear(). For interactive prompts the cost is irrelevant, so creating a new String per iteration is simpler and harder to get wrong.
Why end of input must be checked first
Consider a loop that does not check for Ok(0):
use std::io;
fn main() -> io::Result<()> {
let mut line = String::new();
loop {
line.clear();
io::stdin().read_line(&mut line)?; // result ignored
if let Ok(n) = line.trim().parse::<u32>() {
println!("got {n}");
break;
}
println!("Try again.");
}
Ok(())
}Run this with cargo run < /dev/null, or press Ctrl-D at the prompt (Ctrl-Z then Enter on Windows). Once input has ended, every call to read_line returns Ok(0) immediately and leaves line empty. An empty string never parses as a number, so the program prints "Try again." forever and uses a full CPU core while doing so.
This is the most common bug in retry loops. The rule is to treat Ok(0) as its own case before looking at the text. A blank line the user typed is different: pressing Enter alone gives "\n", so read_line returns Ok(1). That is a parse failure, not the end of input.
Checking more than the type
Parsing only proves the text has the right shape. A u32 can still be 0 or 4000000000. To validate the value, add a second check after a successful parse.
use std::io::{self, Write};
fn ask_age() -> io::Result<Option<u32>> {
let stdin = io::stdin();
loop {
print!("Enter your age (1-120): ");
io::stdout().flush()?;
let mut line = String::new();
if stdin.read_line(&mut line)? == 0 {
return Ok(None);
}
match line.trim().parse::<u32>() {
Ok(n) if (1..=120).contains(&n) => return Ok(Some(n)),
Ok(n) => println!("{n} is outside the range 1 to 120."),
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 age given."),
}
Ok(())
}Two design choices are worth noting.
- The return type is
io::Result<Option<u32>>. The outerResultcarries real I/O failures. The innerOptionsays whether the user supplied a value (Some) or input ended first (None). The caller can tell "the terminal broke" apart from "the user closed the input". - The
Ok(n) if ...arm is a match guard. The match arms are tried in order, so a number that fails the guard falls through to the secondOk(n)arm, which prints the range message.
The flow of the loop
Only one path leads back to the prompt: the one that follows a message about bad text. Every other path leaves the loop.
A reusable prompt function
If the program asks several questions, copying the loop is tedious. Because parse works with any type that implements FromStr, the loop can be generic over the target type.
use std::io::{self, Write};
use std::str::FromStr;
fn prompt<T: FromStr>(message: &str) -> io::Result<Option<T>> {
let stdin = io::stdin();
loop {
print!("{message}");
io::stdout().flush()?;
let mut line = String::new();
if stdin.read_line(&mut line)? == 0 {
return Ok(None);
}
match line.trim().parse::<T>() {
Ok(value) => return Ok(Some(value)),
Err(_) => println!("That is not a valid value. Try again."),
}
}
}
fn main() -> io::Result<()> {
let Some(width) = prompt::<f64>("Width: ")? else {
return Ok(());
};
let Some(height) = prompt::<f64>("Height: ")? else {
return Ok(());
};
println!("Area: {}", width * height);
Ok(())
}The call prompt::<f64> names the type with a turbofish. The compiler could also infer it from how the result is used, but the turbofish makes the choice visible at the call site.
This version discards the parse error with Err(_), because T::Err is not required to implement Display here. If you want to show the specific error, add the bound T::Err: std::fmt::Display and print it. The trade-off is a more complicated signature in exchange for better messages.
The let ... else form keeps the "input ended" case short. It requires Rust 1.65 or later.
Limiting the number of attempts
Interactive users can be trusted to give up. Scripts feeding input through a pipe cannot. If a script pipes the same bad line repeatedly, the loop would keep rejecting it until the data runs out. That is acceptable because the pipe ends. Still, you may prefer a hard limit so a faulty script fails quickly with a clear message.
use std::io::{self, Write};
fn main() -> io::Result<()> {
const MAX_TRIES: u32 = 3;
let stdin = io::stdin();
for attempt in 1..=MAX_TRIES {
print!("Enter a port (attempt {attempt} of {MAX_TRIES}): ");
io::stdout().flush()?;
let mut line = String::new();
if stdin.read_line(&mut line)? == 0 {
eprintln!("input ended");
std::process::exit(1);
}
if let Ok(port) = line.trim().parse::<u16>() {
println!("Using port {port}");
return Ok(());
}
println!("Not a valid port.");
}
eprintln!("too many invalid attempts");
std::process::exit(1);
}Messages for failures go to standard error with eprintln!, and the process exits with a nonzero status so that a calling script can detect the failure. Normal prompts stay on standard output.
Common mistakes
- Using
unwrap()on the parse result. A typo then crashes the program, which is the opposite of what a retry loop is for. - Forgetting
flush(). The loop still works, but the user may not see the prompt before the program waits. - Not checking
Ok(0). The loop spins forever once input is closed. - Reusing a
Stringwithoutclear(). Old text accumulates and every later attempt fails. - Retrying on
io::Error. A failed read usually repeats. Propagate it with?. - Parsing without
trim(). The trailing\nmakes"42\n".parse::<u32>()fail every time, so the loop never accepts valid input.
Summary of the pattern
- Print the prompt and flush standard output.
- Read into a fresh
String, using?for I/O errors. - If the byte count is
0, input has ended, so leave the loop. - Trim and parse. On failure, print a specific message and continue.
- Apply any further checks on the value. On failure, print a message and continue.
- Return the value.
Exercise
The loop below is meant to ask for a number until the user types a valid one. It works when a user types, but cargo run < empty.txt (an empty file) never stops. Explain why and fix it. Keep the function's behavior the same for typed input.
use std::io;
fn readnumber() -> io::Result<i32> {
loop {
let mut line = String::new();
io::stdin().readline(&mut line)?;
if let Ok(n) = line.trim().parse::<i32>() {
return Ok(n);
}
println!("Try again.");
}
}
Show answer
With an empty file, every read_line call returns Ok(0) and leaves line empty. The empty string never parses as an i32, so the loop prints "Try again." forever. The fix is to check the byte count and return an error when input has ended. For example, change the read to if io::stdin().read_line(&mut line)? == 0 { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "input ended")); }. Alternatively, change the return type to io::Result<Option<i32>> and return Ok(None). Typed input behaves as before, since read_line returns a positive count for any line that includes a newline.
Exercise
Write a function ask_yes_no(message: &str) -> io::Result<Option<bool>> that accepts y, yes, n, or no in any letter case, asks again for anything else, and returns Ok(None) when input ends.
Show answer
use std::io::{self, Write}; fn askyesno(message: &str) -> io::Result<Option<bool>> { let stdin = io::stdin(); loop { print!("{message} (y/n): "); io::stdout().flush()?; let mut line = String::new(); if stdin.readline(&mut line)? == 0 { return Ok(None); } match line.trim().tolowercase().asstr() { "y" | "yes" => return Ok(Some(true)), "n" | "no" => return Ok(Some(false)), => println!("Please answer y or n."), } } }