Sub topic 3
Asking Again Until the Input Is Valid
This chapter assumes basic Rust syntax, ownership of String and &str, match, Result, and running programs with cargo run.
Asking Again Until the Input Is Valid
A loop can prompt repeatedly until parsing succeeds. read_line returns Ok(0) when input ends, so the program can also stop cleanly at end-of-file.
use std::io::{self, Write};
fn main() -> io::Result<()> {
loop {
print!("Enter a number: ");
io::stdout().flush()?;
let mut line = String::new();
if io::stdin().read_line(&mut line)? == 0 {
break;
}
match line.trim().parse::<i32>() {
Ok(number) => {
println!("You entered {number}.");
break;
}
Err(_) => println!("Please enter a whole number."),
}
}
Ok(())
}trim removes the newline. parse converts the remaining text to i32, or returns an error.
Processing Many Lines with `lines()`
For piped or redirected input, lock standard input and iterate over its lines:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
for line in io::stdin().lock().lines() {
println!("{}", line?);
}
Ok(())
}The lines() iterator removes each line’s trailing newline. Each item is still a Result<String, io::Error>.
Splitting a Line into Values
Use split_whitespace() to turn a line into tokens. Parse each token separately:
let total: i64 = line
.split_whitespace()
.filter_map(|word| word.parse::<i64>().ok())
.sum();This example skips tokens that are not valid numbers.
Reading All Standard Input at Once
Import the Read trait and call read_to_string when the complete input fits comfortably in memory:
use std::io::{self, Read};
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;This is useful when processing needs to see the whole document.
Returning Mixed Errors
A function that performs both I/O and parsing can return Result<T, Box<dyn std::error::Error>>. The boxed error can hold either error type:
fn read_number<R: std::io::BufRead>(
reader: R,
) -> Result<i32, Box<dyn std::error::Error>> {
let mut line = String::new();
reader.read_line(&mut line)?;
Ok(line.trim().parse()?)
}Writing Input Code You Can Test
Accept a generic BufRead instead of reading stdin directly. Tests can then pass b"42\n".as_slice() as in-memory input.
Exercise
Why should a prompt be followed by stdout().flush()?
Show answer
print! does not add a newline, so flushing makes the prompt visible before the program waits for input.