Sub topic 9
Processing Many Lines with a Locked stdin and lines()
This chapter assumes you know basic Rust syntax, String and &str, Result, and how to run a program with cargo run. You should also have seen read_line and parse in earlier chapters.
Why read_line is awkward for many lines
read_line reads one line per call. To handle a whole stream you must write a loop, create a buffer, and check for Ok(0) yourself. You must also clear or recreate the buffer each time, or new text is appended to the old text.
Rust offers a simpler tool for this case. The lines() method gives you an iterator, so you can use a for loop and let it stop at the end of input.
Locking stdin
io::stdin() returns a handle that many parts of a program can share. Each read through it takes an internal lock for that single call. lock() takes the lock once and returns a StdinLock, which implements the BufRead trait. lines() is a BufRead method, so you need the lock and the trait in scope.
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let mut sum: i64 = 0;
for line in io::stdin().lock().lines() {
let line = line?;
for token in line.split_whitespace() {
match token.parse::<i64>() {
Ok(n) => sum += n,
Err(_) => eprintln!("skipping {token:?}"),
}
}
}
println!("sum = {sum}");
Ok(())
}Try it by piping text into the program:
// shell: printf '1 2 3\n4 five 6\n' | cargo run
// stdout: sum = 16
// stderr: skipping "five"What lines() gives you
Each item the iterator yields is an io::Result<String>. Two details matter:
- The
Stringhas no trailing newline.lines()removes\n, and it also removes\r\n. You do not needtrimjust to drop the line ending. - Each item can be an
Err, because reading can fail. Theline?in the example unwraps it and returns the error frommain.
The loop ends when the input ends. This is the same end-of-input condition that read_line reports as Ok(0), so you no longer check for it by hand.
Common errors
- A missing
use std::io::BufRead. Without the trait in scope, the compiler reports that no method namedlinesexists onStdinLock. Add the import. - Confusing the two
lines()methods.str::lines()splits a string you already hold and yields&str.BufRead::lines()reads from a source and yieldsio::Result<String>. Their item types differ. - Forgetting the
Result. Callingline.split_whitespace()directly on the item fails to compile. Unwrap it first with?,expect, or amatch. - Mixing
lock()with other reads. While aStdinLockis alive, callingio::stdin().read_line(...)in the same thread waits forever for a lock that you already hold. Use the lock for every read in that scope.
Stopping early
A for loop can use break like any other. For example, you can stop at the first blank line:
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() {
break;
}
count += 1;
}
println!("{count} lines before the first blank one");
Ok(())
}Because lines() is an iterator, adapters such as take, filter, and map also work on it. Keep in mind that each item is still a Result.
Exercise
A program loops with for line in io::stdin().lock().lines(). Input is "10\r\n20\r\n". What do the two String values contain, and what happens when the input ends?
Show answer
The values are "10" and "20", with no \r\n because lines() strips both \n and \r\n. After the second item the iterator returns None, so the for loop ends without any explicit end-of-input check.