如果可以失败,从stdin读取几个整数的最简单方法是什么?

Ole*_*sky 8 rust

假设我期望一个来自stdin的3个整数的行.阅读和解析它们最简单的方法是什么?什么是a, b, c = map(int, input().split())在Python或scanf("%d %d %d", &a, &b, &c);C中的Rust等价物?

我提出的最好方法是:

let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let parts: Vec<&str> = line.split_whitespace().collect();
let a: i32 = parts[0].parse().unwrap();
let b: i32 = parts[1].parse().unwrap();
let c: i32 = parts[2].parse().unwrap();
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?

DK.*_*DK. 10

你可以使用scan-rules这个:

/*!
Add this to your `Cargo.toml`, or just run with `cargo script`:

```cargo
[dependencies]
scan-rules = "0.1.1"
```
*/
#[macro_use] extern crate scan_rules;

fn main() {
    print!("Enter 3 ints: ");
    readln! {
        (let a: i32, let b: i32, let c: i32) => {
            println!("a, b, c: {}, {}, {}", a, b, c);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你想做更多涉及的事情,你可以使用多个规则和类型推断,并指定如果输入与给定的任何规则(默认为panic!s)不匹配时该怎么做:

    readln! {
        // Space-separated ints
        (let a: i32, let b: i32, let c: i32) => {
            println!("a b c: {} {} {}", a, b, c);
        },

        // Comma-separated ints, using inference.
        (let a, ",", let b, ",", let c) => {
            let a: i32 = a;
            let b: i32 = b;
            let c: i32 = c;
            println!("a, b, c: {}, {}, {}", a, b, c);
        },

        // Comma-separated list of *between* 1 and 3 integers.
        ([let ns: i32],{1,3}) => {
            println!("ns: {:?}", ns);
        },

        // Fallback if none of the above match.
        (..line) => {
            println!("Invalid input: {:?}", line);
        }
    }
Run Code Online (Sandbox Code Playgroud)

免责声明:我是作者scan-rules.


oli*_*obk 7

你可以使用text_io这个:

#[macro_use] extern crate text_io;

fn main() {
    // reads until a whitespace is encountered
    let a: i32 = read!();
    let b: i32 = read!();
    let c: i32 = read!();
}
Run Code Online (Sandbox Code Playgroud)

text_io 0.1.3还支持一个scan!宏:

let (a, b, c): (i32, i32, i32);
scan!("{}, {}, {}\n", a, b, c);
Run Code Online (Sandbox Code Playgroud)

如果您想从文件或其他来源读取,您还可以在任何实现的类型上使用这两个宏Iterator<Item=u8>:

use std::io::Read;
let mut file = std::fs::File::open("text.txt").unwrap()
                                              .bytes()
                                              .map(Result::unwrap);
let x: i32 = read!("{}\n", file);
Run Code Online (Sandbox Code Playgroud)

要么

let (x, y, z): (i32, i32, i32);
scan!(file => "{}, {}: {}", x, y, z);
Run Code Online (Sandbox Code Playgroud)

: i32如果编译器可以从上下文推断出这些类型,则可以不使用s.

免责声明:我是作者text_io.