如何从单行标准输入中读取多个整数? [英] How do I read multiple integers from a single line of stdin?

查看:46
本文介绍了如何从单行标准输入中读取多个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了学习 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.

这篇关于如何从单行标准输入中读取多个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆