What's the easiest way to read several ints from stdin if it's ok to fail?

Viewed 1772

Suppose I expect a line with 3 integers from stdin. What's the easiest way to read and parse them? What's the Rust equivalent of a, b, c = map(int, input().split()) in Python or scanf("%d %d %d", &a, &b, &c); in C?

The best way I came up with was something like:

let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let parts: Vec<&str> = line.split_whitespace().collect();
let a: i32 = parts[0].parse().unwrap();
let b: i32 = parts[1].parse().unwrap();
let c: i32 = parts[2].parse().unwrap();

Is there a simpler way?

3 Answers

I discovered you can use split_whitespace to put the integers in the string into an iterator. Then you unwrap it out of std::option::Option<&str> using unwrap(). After parsing the &str using parse() and unwrapping its result using unwrap(), you have an integer if you have specified the type of variable using variable_name: i32 = ...:

let mut numbers = String::new();
io::stdin()
    .read_line(&mut numbers)
    .ok()
    .expect("read error");
let mut iter = numbers.split_whitespace();
let mut x: i32 = iter.next().unwrap().parse().unwrap();
let mut y: i32 = iter.next().unwrap().parse().unwrap();
let mut n: i32 = iter.next().unwrap().parse().unwrap();
println!("{},{},{}", x, y, n);
Related