Sub topic 7
Detecting End of Input
This chapter assumes you can read a line with read_line, handle its io::Result with ? or expect, and trim and parse the text. If a loop that re-prompts on bad input is new to you, a quick look at that earlier chapter will help. Here you will learn how a program learns that no more input will ever arrive, and why a loop that ignores this can run forever.
What end of input means
Standard input is a stream of bytes. Sometimes the stream stops, and the program can tell the stop is permanent. This is called end of input, or end-of-file (EOF). It is not an error. It is the normal way a stream finishes.
EOF happens in several situations:
- Interactive terminal: you press Ctrl-D on Linux and macOS. On Windows you press Ctrl-Z, then Enter.
- Redirected file:
cargo run < data.txtends when the file ends. - Pipe:
printf '1\n2\n' | cargo runends when the program on the left exits or closes its output. - No input at all:
cargo run < /dev/nullgives EOF immediately.
A program that only works when someone is typing at it will misbehave in the last three cases. Detecting EOF is what makes a program usable in scripts and pipelines.
How read_line reports it
read_line returns io::Result<usize>. On success, the number is how many bytes were appended to your String. At EOF, nothing can be appended, so the count is 0.
| Situation | Return value | Buffer after the call |
|---|---|---|
| User typed `hi` and pressed Enter | `Ok(3)` | `"hi\n"` |
| User pressed Enter on an empty line | `Ok(1)` | `"\n"` |
| Last line of a file has no trailing newline: `hi` | `Ok(2)` | `"hi"` |
| Input has ended | `Ok(0)` | unchanged |
| Input is not valid UTF-8 | `Err(...)` | unchanged |
The second row is the one people confuse. An empty line is not EOF. The newline character itself counts as one byte, so the result is Ok(1). Only Ok(0) means the stream is finished.
Here is the complete pattern, which stops the loop when it sees Ok(0):
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 ? after read_line handles real I/O failures by returning them from main. The comparison == 0 then handles the normal end of the stream. The println!() prints a blank line so the shell prompt does not appear on the same line as your last prompt.
The infinite loop you get without it
Suppose you leave out the check:
use std::io::{self, Write};
fn main() -> io::Result<()> {
loop {
print!("Enter a number: ");
io::stdout().flush()?;
let mut line = String::new();
io::stdin().read_line(&mut line)?;
match line.trim().parse::<f64>() {
Ok(n) => println!("{n} squared is {}", n * n),
Err(_) => println!("Please enter a number."),
}
}
}Run it with cargo run < /dev/null. The first read_line returns Ok(0) and leaves line empty. An empty string does not parse as a number, so the program prints "Please enter a number." and loops. The next read_line returns Ok(0) again, because a finished stream stays finished. The program prints the same message forever and uses a full CPU core.
Nothing in the code looks wrong. The retry logic is correct for a person who made a typo, but EOF is a case where retrying can never succeed. Every retry loop that reads input needs an EOF exit.
Telling EOF apart from errors
EOF and failure are different outcomes, so a match can give each one its own arm. This program echoes lines and reports what happened:
use std::io::{self, Write};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let mut line = String::new();
loop {
line.clear();
print!("> ");
io::stdout().flush()?;
match stdin.read_line(&mut line) {
Ok(0) => {
println!("end of input");
break;
}
Ok(n) => println!("read {n} bytes: {line:?}"),
Err(e) => {
eprintln!("read error: {e}");
return Err(e);
}
}
}
Ok(())
}Two details matter here.
First, read_line appends to the string. This version reuses one String across iterations, so it calls line.clear() at the top of the loop. Without that, each line would be added to all the previous ones. The earlier examples created a new String inside the loop, which avoids the problem but allocates each time.
Second, the Err arm is rare but real. The most common cause is input that is not valid UTF-8. read_line then returns an error of kind InvalidData, and the bytes it consumed are not placed in your string. That is a failure, not an end of input, so the program reports it and stops rather than treating it as EOF.
Input that ends without a newline
Files and pipes often end without a final newline. Try this in a shell:
printf 'a\nb' | cargo runThe calls return, in order:
Ok(2)with"a\n".Ok(1)with"b".Ok(0).
The second line has no \n, yet it is valid data. The program must process it before it sees EOF. The Ok(n) arm does this naturally, because it runs for any positive count. A common mistake is to check line.ends_with('\n') to decide whether a line is complete, which silently drops the last line of such input. Using trim() before parsing handles both forms, since it removes a trailing newline if there is one and does nothing otherwise.
EOF with the other reading methods
read_line is not the only way to read, and each method reports EOF in its own way.
| Method | How the end shows up |
|---|---|
| `read_line` | Returns `Ok(0)` |
| `lines()` on a locked stdin | The iterator returns `None`, so the `for` loop ends on its own |
| `read_to_string` | Reads until EOF by design and returns the total byte count; empty input gives `Ok(0)` |
With lines() you do not write an EOF check at all. The loop ends when the stream does:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut count = 0;
for line in io::stdin().lock().lines() {
let line = line?;
if !line.trim().is_empty() {
count += 1;
}
}
println!("{count} non-empty lines");
Ok(())
}Each item is an io::Result<String>, so errors still arrive as Err items, and ? returns them. The strings have no trailing newline.
read_to_string is the opposite approach. It waits for EOF and gives you everything at once. That means a terminal user must press Ctrl-D before the program does anything, and the whole input must fit in memory. For interactive prompts, use read_line. For batch data, lines() or read_to_string is usually simpler.
Edge cases at the terminal
A few behaviors surprise people when they test by hand:
- Ctrl-D on a non-empty line (Linux and macOS): the first press delivers the text typed so far without a newline, so
read_linereturnsOk(n)withn > 0. A second press on the empty line givesOk(0). This is a terminal convention, not Rust behavior. - Ctrl-C is not EOF: it sends an interrupt signal and ends the process by default. Your code never sees a return value.
- EOF is sticky for pipes and files, but not guaranteed for terminals: on some systems a terminal can deliver more input after Ctrl-D. Do not rely on reading again after
Ok(0). Once you see it, stop. - Windows line endings: a file with
\r\nends each line with two characters.trim()removes both, but a check such asline == "\n"would fail.
Summary of the rules
Ok(0)fromread_linemeans the stream is finished. Leave the loop.Ok(1)with"\n"is a blank line, not EOF.Err(_)is a real failure and should be reported or returned.- Process any positive count, even if it lacks a newline.
lines()andread_to_stringhandle EOF for you, and you only need to deal with their errors.
Exercise
A program reads numbers in a loop with read_line. When you run it with cargo run < /dev/null, it prints "Please enter a number." over and over and never stops. What is the cause, and what is the smallest change that fixes it?
Show answer
With no input, every call to read_line returns Ok(0) and leaves the buffer empty. The empty string fails to parse, so the program takes the "invalid input" path and loops again, and the next read returns Ok(0) again. The fix is to check the returned count and break when it is zero, for example if stdin.read_line(&mut line)? == 0 { break; }, before trimming and parsing.
Exercise
You run printf '5\n7' | cargo run against a program that sums the numbers on each line using read_line. It prints 5 instead of 12, and its loop only processes a line when line.ends_with('\n'). Why is 7 lost, and how should the loop decide whether a line is usable?
Show answer
The last line 7 has no trailing newline, so ends_with('\n') is false and the program skips it, even though read_line returned Ok(1) for it. The loop should not inspect the newline. It should process any read whose count is greater than zero, call trim() before parsing (which works with or without a newline), and stop only when read_line returns Ok(0).