Module 4Reading Input (stdin)Lesson 6 of 2316 min
Real stdin API (copy-paste for local)
io::stdin, BufRead, fast-ish patterns you will use in contests.
Minimal local template
rust
// Local version (real stdin). On this site, use the simulated version in the exercise.
use std::io::{self, Read};
fn main() {
let mut s = String::new();
io::stdin().read_to_string(&mut s).unwrap();
let mut it = s.split_whitespace();
let n: usize = it.next().unwrap().parse().unwrap();
let mut xs = Vec::with_capacity(n);
for _ in 0..n {
xs.push(it.next().unwrap().parse::<i32>().unwrap());
}
println!("{n} {:?}", xs);
}Output
3 [10, 20, 30]Why read_to_string + split_whitespace?
Simple and fine for most interview sizes. Contests sometimes use bulk reads for speed.
On this website
Run the simulated version below (string input). Locally, swap in real stdin.
Macro-style next token helper
rust
fn next<T: std::str::FromStr>(it: &mut impl Iterator<Item = &str>) -> T {
it.next().unwrap().parse().ok().unwrap()
}Challenge
Write next::<T> generic helper using FromStr and parse two f64s.
Tips
- read_to_string for whole input
- split_whitespace tokenizes all
- Same logic for local contests
Try it live
Real stdin API (copy-paste for local)Rust 2021
Loading editor…
Output
Press Run to compile and execute.