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

后端 未结 7 1973
栀梦
栀梦 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:47

    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::() {
            Ok(i) => println!("your integer input: {}", i),
            Err(..) => println!("this was not an integer: {}", trimmed),
        };
    }
    

提交回复
热议问题