Sub topic 7
Detecting end of input
This chapter assumes you can already call read_line, handle its io::Result with ?, and use trim and parse. Here you learn how a program notices that no more input is coming.
What end of input means
Standard input is a stream of bytes. At some point the stream can end:
- In a terminal on Linux or macOS, you press Ctrl-D on an empty line.
- In a Windows console, you press Ctrl-Z and then Enter.
- With piped data (
cat numbers.txt | cargo run) or redirected data (cargo run < numbers.txt), the stream ends when the file or the producing program finishes.
This state is called end of input, or EOF (end of file). It is not an error. The read succeeds and simply finds nothing.
The Ok(0) signal
read_line returns io::Result<usize>. The number inside Ok is how many bytes were appended to your String. A blank line the user typed is still the one byte "\n", so it returns Ok(1). Only a stream with nothing left returns Ok(0).
| Situation | Result | Contents added to the `String` |
|---|---|---|
| User types `42` and Enter | `Ok(3)` on Unix (`"42\n"`) | `"42\n"` |
| User presses Enter on an empty line | `Ok(1)` | `"\n"` |
| Last line of a file has no trailing newline | `Ok(n)` with `n > 0` | the text only |
| Stream is finished | `Ok(0)` | nothing |
Checking trim().is_empty() is not a substitute. It cannot tell a blank line from EOF.
A loop that stops at EOF
This program reads numbers until the input ends. Invalid text prints a message and prompts again.
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(())
}The ? on read_line handles real I/O failures. The comparison with 0 handles the normal end of the stream. The println!() after EOF moves the cursor to a fresh line, because the user never typed a newline.
The common error: an endless loop
Suppose you forget the zero check and write only the match. At EOF, read_line returns Ok(0) and leaves line empty. "".parse::<f64>() fails, so the program prints "Please enter a number." Then it reads again, gets Ok(0) again, and repeats forever. A piped program that hangs at 100% CPU, printing the same message, almost always has this bug.
Test your loop without a terminal:
printf '3\nabc\n4' | cargo runThe final 4 has no newline. A correct loop still processes it, because that read returns Ok(1), and it stops on the next call.
Other ways EOF shows up
lines()on a locked stdin handle returnsNoneat EOF, so aforloop just ends. You do not check for zero yourself.read_to_stringreads until EOF and returns the total byte count. An empty input givesOk(0)and an emptyString.
Both are covered in later chapters. The idea is the same: the stream ran out.
Reusing the buffer
read_line appends to the String; it does not replace its contents. If you declare line outside the loop for efficiency, call line.clear() before each read. Otherwise old text stays in the buffer and gets parsed again. At EOF, the zero return value is still correct, but the buffer holds the previous line. Creating a new String inside the loop, as above, avoids the problem.
Exercise
A loop reads with stdin.read_line(&mut line)?, trims, and calls parse::<i32>(). On Err it prints "Try again" and continues. When you run it with cargo run < empty.txt, where the file is empty, it prints "Try again" forever. Why, and what is the fix?
Show answer
The file is empty, so every read_line call returns Ok(0) and leaves line empty. Parsing an empty string always fails, so the loop never ends. Store the result of read_line, and break (or return) when it equals 0, before trimming and parsing.