为了学习 Rust,我正在关注 HackerRank 30 天挑战、Project Euler 和其他编程竞赛。我的第一个障碍是从单行标准输入中读取多个整数。
在 C++ 中我可以方便地说:
cin >> n >> m;
我如何在 Rust 中以惯用的方式做到这一点?
最佳答案
据我所知,最好的方法就是拆分输入行,然后将它们映射到整数,如下所示:
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.
请注意,如果输入无效,这将崩溃!
;你应该改为 handle the result values properly如果你想避免这种情况。
关于rust - 如何从单行标准输入中读取多个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39439582/