如何在Rust 1.0中读取用户的整数输入?

sun*_*ica 13 integer user-input input rust

我发现的现有答案都是基于from_str(例如 有效地从控制台读取用户输入),但显然from_str(x)已经改变为x.parse()Rust 1.0.作为一个新手,考虑到这一变化,原始解决方案应该如何适应并不明显.

从Rust 1.0开始,从用户那里获取整数输入的最简单方法是什么?

Mic*_*ael 33

这是一个包含所有可选类型注释和错误处理的版本,对于像我这样的初学者可能会有用:

use std::io;

fn main() {
    let mut input_text = String::new();
    io::stdin()
        .read_line(&mut input_text)
        .expect("failed to read from stdin");

    let trimmed = input_text.trim();
    match trimmed.parse::<u32>() {
        Ok(i) => println!("your integer input: {}", i),
        Err(..) => println!("this was not an integer: {}", trimmed),
    };
}
Run Code Online (Sandbox Code Playgroud)


cod*_*101 11

如果您正在寻找一种读取输入的方法,以便在您无法访问的 codeforces 等网站上进行竞争性编程,那么text_io此解决方案适合您。

我使用以下宏从 读取不同的值stdin

use std::io;

#[allow(unused_macros)]
macro_rules! read {
    ($out:ident as $type:ty) => {
        let mut inner = String::new();
        io::stdin().read_line(&mut inner).expect("A String");
        let $out = inner.trim().parse::<$type>().expect("Parseble");
    };
}

#[allow(unused_macros)]
macro_rules! read_str {
    ($out:ident) => {
        let mut inner = String::new();
        io::stdin().read_line(&mut inner).expect("A String");
        let $out = inner.trim();
    };
}

#[allow(unused_macros)]
macro_rules! read_vec {
    ($out:ident as $type:ty) => {
        let mut inner = String::new();
        io::stdin().read_line(&mut inner).unwrap();
        let $out = inner
            .trim()
            .split_whitespace()
            .map(|s| s.parse::<$type>().unwrap())
            .collect::<Vec<$type>>();
    };
}
  
Run Code Online (Sandbox Code Playgroud)

如下使用


fn main(){
   read!(x as u32);
   read!(y as f64);
   read!(z as char);
   println!("{} {} {}", x, y, z);

   read_vec!(v as u32); // Reads space separated integers and stops when newline is encountered.
   println!("{:?}", v);
}

Run Code Online (Sandbox Code Playgroud)


Dan*_*ath 9

可能最简单的部分是使用text_io crate并写:

#[macro_use]
extern crate text_io;

fn main() {
    // read until a whitespace and try to convert what was read into an i32
    let i: i32 = read!();
    println!("Read in: {}", i);
}
Run Code Online (Sandbox Code Playgroud)

如果您需要同时读取多个值,则可能需要每晚使用Rust.


qed*_*qed 7

以下是几种可能性(Rust 1.7):

use std::io;

fn main() {
    let mut n = String::new();
    io::stdin()
        .read_line(&mut n)
        .expect("failed to read input.");
    let n: i32 = n.trim().parse().expect("invalid input");
    println!("{:?}", n);

    let mut n = String::new();
    io::stdin()
        .read_line(&mut n)
        .expect("failed to read input.");
    let n = n.trim().parse::<i32>().expect("invalid input");
    println!("{:?}", n);

    let mut n = String::new();
    io::stdin()
        .read_line(&mut n)
        .expect("failed to read input.");
    if let Ok(n) = n.trim().parse::<i32>() {
        println!("{:?}", n);
    }
}
Run Code Online (Sandbox Code Playgroud)

这些使您免于模式匹配的麻烦,而无需依赖其他库。

  • 来吧,它显然不同,完整的答案使读者更容易。 (3认同)
  • 明确地说,随时留下答案,其他人可能会发现它有用并赞成。只要有散文来描述它为何与众不同和更好,那是一个有效的答案! (2认同)