Rust:Rust Stdin入力:io::stdin().lock() で安全に行を読み取る
Rust•Stdinパース

Rust Stdin入力:io::stdin().lock() で安全に行を読み取る

Compilraのrustc 1.85では実行前にすべてのstdinが渡されます。io::stdin().lock() を最初に1回だけ取得することで行ごとのミューテックス負荷をなくし、BufRead 経由で数値スライスを安全に解析できます。

構文

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

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
io::stdin().lock()StdinLock標準入力に対するバッファ付き排他ロックを取得し、BufRead トレイトを利用可能にします。
BufRead::lines()Lines<StdinLock>末尾の改行を取り除いた Result<String, io::Error> を1行ずつ生成します。
.split_whitespace()SplitWhitespace中間Vecを確保せずにUnicode/ASCII空白文字でスライスを分割します。

そのまま実行できるコード例

Compilra で実行可能

Rust をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

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);
        }
    }
}
事前入力 Stdin (入力):
2
10 20 30
5 15 25 35
期待される出力:
Case #1: count=3, sum=60
Case #2: count=4, sum=80

動作のしくみ: ステップ解説

  • 4-5行目: io::stdin() を1回ロックし、BufRead の行イテレータを取得します。
  • 7-11行目: 1行目を安全に読み取り、.unwrap_or(0) 付きで case_count をパースします。
  • 13-22行目: 各ケース行を空白で分割し、filter_map で整数変換した合計を出力します。

重要ポイント

  • 実行前にStandard Input (stdin)欄へテストケースを入力してください(対話型ではなく事前供給方式です)。
  • read_line(&mut buf) でStringバッファをクリアせず再利用すると前の行の後ろに追記されますが、BufRead::lines() なら安全です。
  • .filter_map(|t| t.parse::<i32>().ok()) を使うと余分な空白があってもパニックを防げます。

よくある間違い: buf.clear() を呼ばずに read_line(&mut buf) で String を再利用する

Stdin::read_line は既存バッファを上書きせず末尾へ追記するため、次のパース結果が壊れます。

❌ 誤り
let mut buf = String::new();
for _ in 0..2 {
    io::stdin().read_line(&mut buf).unwrap(); // Appends without clearing!
}
✅ 正しい例
let mut buf = String::new();
for _ in 0..2 {
    buf.clear();
    io::stdin().read_line(&mut buf).unwrap();
}

関連するRustチュートリアルとコンパイラ

Compilra で Rust を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。