Rs
Module 4Reading Input (stdin)Lesson 5 of 2324 min

Common Input Patterns

n then n lines; n m grid; until EOF; strings with spaces.

Pattern A — n, then one line of n ints

5
1 4 2 8 5

Pattern B — n, then n lines of pairs

3
1 2
3 4
5 6

Pattern C — read all tokens (flexible)

rust
let tokens: Vec<&str> = input.split_whitespace().collect();
let mut it = tokens.into_iter();
let n: usize = it.next().unwrap().parse().unwrap();

Strings

  • Token string: split_whitespace
  • Full line (spaces kept): use the whole line after header

Multiple test cases

Often first token t, then loop t times.

Challenge

Parse t test cases each with an array: first t, then for each case n and n ints.

Tips
  • Iterator over lines
  • with_capacity(n)
  • Token stream is robust

Try it live

Common Input PatternsRust 2021
Loading editor…
Output
Press Run to compile and execute.