Read and validate console input
Read and validate console input
A typed mark from a user arrives as text, not as a validated number. Reading, parsing and validation are separate steps. Standard input can fail, contain invalid text or reach its end, so a useful program handles those situations deliberately.
What you’ll learn
- Handle valid text, invalid text and end of input separately.
- Accept a mark only after both parsing and range validation.
Read and validate console input in action
Read bytes: 80 plus newline
With sample input 80 followed by a newline, read_line fills the buffer.
Read bytes: 80 plus newlineTrim and parse: 80
Trim leaves 80, parsing returns Ok(80), and the guard accepts its range.
Trim and parse: 80Validate and record: 80
Invalid text takes the fallback arm; end of input takes the separate Ok(0) arm.
Validate and record: 80
Read and validate console input explained
read_line appends into a mutable String and returns a Result containing the number of bytes read. Trim removes surrounding whitespace, including the newline. Parsing into u32 rejects nonnumeric text and negative integers; a separate comparison rejects marks above 100.
Connect this idea with result and recoverable errors.
Work through the Rust program
Save the complete source as main.rs in the Rust environment. Supply sample standard input 80 followed by a newline.
Rust 2024 · complete program
use std::io;
fn main() {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(0) => println!("No input supplied"),
Ok(_) => match input.trim().parse::<u32>() {
Ok(score) if score <= 100 => println!("Recorded: {score}"),
_ => println!("Enter a whole mark from 0 to 100"),
},
Err(_) => println!("Could not read input"),
}
}Expected output
Recorded: 80Follow the execution
With sample input 80 followed by a newline, read_line fills the buffer. Trim leaves 80, parsing returns Ok(80), and the guard accepts its range. Invalid text takes the fallback arm; end of input takes the separate Ok(0) arm.
Try the complete program in the Rust compiler. For tests, Cargo commands and local files, use the specified local environment.
Try a small variation
Your task: What should happen when the user enters 120?
Rust 2024 · complete program
use std::io;
fn main() {
let mut input = String::new();
match io::stdin().read_line(&mut input) {
Ok(0) => println!("No input supplied"),
Ok(_) => match input.trim().parse::<u32>() {
Ok(score) if score <= 100 => println!("Recorded: {score}"),
_ => println!("Enter a whole mark from 0 to 100"),
},
Err(_) => println!("Could not read input"),
}
}Worked answer
The program should print Enter a whole mark from 0 to 100. Parsing succeeds, but the range guard rejects the value.
Mistakes and limits to recognize
Reusing a buffer without clearing it can accumulate multiple lines. End of input is not identical to a blank line. A console example does not validate an HTTP request or provide a graphical input form; those environments have their own input boundaries.
Check your understanding
Take the idea into your next program
The program should print Enter a whole mark from 0 to 100. Parsing succeeds, but the range guard rejects the value. Reusing a buffer without clearing it can accumulate multiple lines.
Further reading: the official Rust Book on read and validate console input.
Reaching the recap and completing the quizzes are separate milestones.