Rust:Rust Stdin Input: Reading Lines Safely with io::stdin().lock()
Rust•Stdin Parsing

Rust Stdin Input: Reading Lines Safely with io::stdin().lock()

In Compilra rustc 1.85, all stdin is passed upfront before clicking Run. Locking io::stdin().lock() once avoids per-line mutex overhead and implements BufRead so you can iterate lines cleanly and parse numeric slices safely.

Syntax

let stdin = io::stdin(); for line in stdin.lock().lines() { ... }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
io::stdin().lock()StdinLockAcquires an exclusive buffered lock on standard input implementing BufRead.
BufRead::lines()Lines<StdinLock>Yields Result<String, io::Error> for each line with trailing newlines stripped.
.split_whitespace()SplitWhitespaceSplits each line on ASCII/Unicode whitespace without allocating an intermediate Vec<&str>.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

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

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    let case_count: usize = lines
        .next()
        .and_then(|res| res.ok())
        .and_then(|s| s.trim().parse().ok())
        .unwrap_or(0);

    for idx in 1..=case_count {
        if let Some(Ok(line)) = lines.next() {
            let nums: Vec<i32> = line
                .split_whitespace()
                .filter_map(|t| t.parse::<i32>().ok())
                .collect();
            let sum: i32 = nums.iter().sum();
            println!("Case #{}: count={}, sum={}", idx, nums.len(), sum);
        }
    }
}
Pre-Supplied Stdin (Input):
2
10 20 30
5 15 25 35
Expected Output:
Case #1: count=3, sum=60
Case #2: count=4, sum=80

How It Works: Step-by-Step

  • Lines 4-5: Locks io::stdin() once and wraps it in a BufRead line iterator.
  • Lines 7-11: Reads the first line safely and parses case_count with .unwrap_or(0) fallback.
  • Lines 13-22: Splits each case line on whitespace, parses integers with filter_map, and sums them.

Key Concepts

  • Enter test cases in Compilra’s Standard Input (stdin) box before clicking Run—stdin is sent upfront rather than typed interactively.
  • Reusing a String buffer with read_line(&mut buf) without clearing it first appends new lines onto old text—BufRead::lines() avoids that bug.
  • Using .filter_map(|t| t.parse::<i32>().ok()) prevents panics when lines contain extra spaces or trailing characters.

Common Mistake: Reusing a String in read_line(&mut buf) without calling buf.clear()

Stdin::read_line appends to the existing buffer rather than overwriting it, corrupting subsequent parses.

❌ Incorrect
let mut buf = String::new();
for _ in 0..2 {
    io::stdin().read_line(&mut buf).unwrap(); // Appends without clearing!
}
✅ Correct
let mut buf = String::new();
for _ in 0..2 {
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
}

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler