Rs
Module 4Reading Input (stdin)Lesson 4 of 2322 min

stdin Basics: lines & tokens

read_line, split_whitespace, parse — real stdin vs playground simulation.

Real interview / CP style (local)

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

fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let n: usize = lines.next().unwrap().unwrap().trim().parse().unwrap();
    // ...
}

Playground / tests: simulate input with a string

Online runners here often have empty stdin, so we practice the same parsing logic on a string:

rust
let input = "3\n1 2 3\nhello world\n";
for line in input.lines() { ... }

Tokens

rust
let nums: Vec<i32> = line
    .split_whitespace()
    .map(|t| t.parse().unwrap())
    .collect();

Tips

  • Always trim() before parse
  • Prefer collecting all tokens if format varies
  • In production, handle Result instead of unwrap
Challenge

Parse safely with Result instead of unwrap for a bad token "x".

Tips
  • trim before parse
  • split_whitespace handles multi-spaces
  • Simulate stdin with string.lines() here

Try it live

stdin Basics: lines & tokensRust 2021
Loading editor…
Output
Press Run to compile and execute.