How to read an integer input from the user in Rust 1.0?

后端 未结 7 1980
栀梦
栀梦 2020-11-30 11:08

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) h

7条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 11:32

    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::().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::() {
            println!("{:?}", n);
        }
    }
    

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

提交回复
热议问题