typestar

Reading standard input in Rust

A filter reads lines from stdin, so it composes with every other tool.

use std::io::{self, BufRead, Write};

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    let stdout = io::stdout();
    let mut out = stdout.lock();

    let mut total = 0usize;
    for line in stdin.lock().lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        total += line.split_whitespace().count();
        writeln!(out, "{:>4} | {}", line.len(), line)?;
    }

    writeln!(out, "{total} words")?;
    Ok(())
}

How it works

  1. stdin().lock().lines() iterates without reallocating.
  2. Each line arrives as a Result, since IO can fail.
  3. Writing to stdout through a lock avoids flushing per line.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
401
Tokens
143
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 82 seconds.

Type this snippet

Step 1 of 1 in Input & output, step 6 of 12 in CLI tools & HTTP clients.

← Previous Next →