How can I convert a string of numbers to an array or vector of integers in Rust?

后端 未结 3 394
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 10:57

I\'m writing on STDIN a string of numbers (e.g 4 10 30 232312) and I want to read that and convert to an array (or a vector) of integers, but I can\'t find the

3条回答
  •  死守一世寂寞
    2020-12-09 11:05

    On Rust 1.5.x, a working solution is:

    fn main() {
        let mut numbers = String::new();
    
        io::stdin()
            .read_line(&mut numbers)
            .ok()
            .expect("read error");
    
        let numbers: Vec = numbers
            .split_whitespace()
            .map(|s| s.parse().expect("parse error"))
            .collect();
    
        for num in numbers {
            println!("{}", num);
        }
    }
    

提交回复
热议问题