如何从单行标准输入中读取多个整数?

问题描述:

为了学习 Rust,我正在寻找诸如 HackerRank 30 天挑战、Project Euler 和其他编程竞赛之类的东西.我的第一个障碍是从单行标准输入中读取多个整数.

To learn Rust, I'm looking at things like the HackerRank 30 days challenge, Project Euler, and other programming contests. My first obstacle is to read multiple integers from a single line of stdin.

在 C++ 中,我可以很方便地说:

In C++ I can conveniently say:

cin >> n >> m;

如何在 Rust 中以惯用方式执行此操作?

How do I do this idiomatically in Rust?

据我所知,最好的方法是将输入行拆分,然后将它们映射到整数,如下所示:

The best way, as far as I know, is just to split the input line and then map those to integers, like this:

use std::io;

let mut line = String::new();
io::stdin().read_line(&mut line).expect("Failed to read line");

let inputs: Vec<u32> = line.split(" ")
    .map(|x| x.parse().expect("Not an integer!"))
    .collect();

// inputs is a Vec<u32> of the inputs.

请注意,如果输入无效,这会恐慌!;如果您希望避免,您应该正确处理结果值这个.

Be aware that this will panic! if the input is invalid; you should instead handle the result values properly if you wish to avoid this.