How to read an integer input from the user in Rust

2019-01-14 23:46发布

Existing answers I've found are all based on from_str (such as Reading in user input from console once efficiently), but apparently from_str(x) has changed into x.parse() in Rust 1.0. As a newbie, it's not obvious how the original solution should be adapted taking this change into account.

As of Rust 1.0, what is the easiest way to get an integer input from the user?

4条回答
别忘想泡老子
2楼-- · 2019-01-14 23:55

Probably the easiest part would be to use the text_io crate and write:

#[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);
}

If you need to read more than one value simultaneously, you might need to use Rust nightly.

查看更多
唯我独甜
3楼-- · 2019-01-14 23:57

Here are a few possibilities (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);
    }
}

These spare you the ceremony of pattern matching without depending on extra libraries.

查看更多
Emotional °昔
4楼-- · 2019-01-15 00:03

Here is a version with all optional type annotations and error handling which may be useful for beginners like me:

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),
    };
}
查看更多
成全新的幸福
5楼-- · 2019-01-15 00:16

parse is more or less the same; it’s read_line that’s unpleasant now.

use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();

    match s.trim_right().parse::<i32>() {
        Ok(i) => println!("{} + 5 = {}", i, i + 5),
        Err(_) => println!("Invalid number."),
    }
}
查看更多
登录 后发表回答