Sub topic 2
Trimming the Trailing Newline
This chapter assumes basic Rust syntax, ownership of String and &str, match, and Result. It also assumes you can run a program with cargo run.
Trim Input Before Parsing
read_line appends the input line and its line ending to a String. If the user types 42 and presses Enter, the string usually contains "42\n". Parsing that value directly can fail because the newline is not part of a number.
Call trim() to remove whitespace from both ends. The returned value is a borrowed &str, so it does not copy the text.
use std::io;
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let age = input.trim().parse::<u32>()?;
println!("Next year: {}", age + 1);
Ok(())
}trim() also removes spaces. If spaces are meaningful, use trim_end() to remove only trailing whitespace.
Parse Text into a Type
parse converts text into a type that implements the FromStr trait. Rust often needs a type annotation because the same text could represent different types.
| Input text | Expression | Result type |
|---|---|---|
| `"42"` | `parse::<u32>()` | `Result<u32, _>` |
| `"3.5"` | `parse::<f64>()` | `Result<f64, _>` |
Parsing can fail, so handle the Result instead of assuming success. A loop can report invalid input and ask again.
Show a Prompt
print! does not automatically flush standard output. The prompt may remain in a buffer while the program waits for input. Import Write and call flush():
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 {
println!();
break;
}
match line.trim().parse::<f64>() {
Ok(number) => println!("Square: {}", number * number),
Err(_) => println!("Please enter a valid number."),
}
}
Ok(())
}Detect End of Input
read_line returns Ok(0) when it reaches end-of-file, meaning no more input exists. This happens when input is piped from a file or the user sends an end-of-file signal. Check this result before parsing an empty string.
Exercise
Why should a program call trim() before parse::<u32>()?
Show answer
read_line includes the trailing newline, and trim() removes it so the remaining text can be parsed as a number.