How to read user input in Rust?

前端 未结 10 1680
情歌与酒
情歌与酒 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:17

    This is what I have come up with (with some help from the friendly people in the #rust IRC channel on irc.mozilla.org):

    use core::io::ReaderUtil;
    
    fn read_lines() -> ~[~str] {
        let mut all_lines = ~[];
    
        for io::stdin().each_line |line| {
            // each_line provides us with borrowed pointers, but we want to put
            // them in our vector, so we need to *own* the lines
            all_lines.push(line.to_owned());
        }
    
        all_lines
    }
    
    fn main() {
        let all_lines = read_lines();
    
        for all_lines.eachi |i, &line| {
            io::println(fmt!("Line #%u: %s", i + 1, line));
        }
    }
    

    And proof that it works :)

    $ rustc readlines.rs
    $ echo -en 'this\nis\na\ntest' | ./readlines
    Line #1: this
    Line #2: is
    Line #3: a
    Line #4: test
    

提交回复
热议问题