How to read user input in Rust?

前端 未结 10 1916
情歌与酒
情歌与酒 2021-01-31 07:50

Editor\'s note: This question refers to parts of Rust that predate Rust 1.0, but the general concept is still valid in Rust 1.0.

I intend to

10条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 08:23

    There are few ways I can think of.

    Read all the input into single String

    let mut input = String::new();
    io::stdin().read_to_end(&mut input);
    

    Read lines into Vector. This one doesn't panic when reading a line fails, instead it skips that failed line.

    let stdin = io::stdin();
    let locked = stdin.lock();
    let v: Vec = locked.lines().filter_map(|line| line.ok()).collect();
    

    Furthermore if you want to parse it:

    After reading it into string do this. You can parse it to other collections that implements FromIterator. Contained elements in the collection also must implement FromStr. As long as the trait constraint satisfies you can change Vec to any Collection:FromIterator, Collection

    let v: Vec = "4 -42 232".split_whitespace().filter_map(|w| w.parse().ok()).collect();
    

    Also you can use it on the StdinLock

    let vv: Vec> = locked
        .lines()
        .filter_map(|l|
            l.ok().map(|s|
                s.split_whitespace().filter_map(|word| word.parse().ok()).collect()
            )
        )
        .collect();
    

提交回复
热议问题