How to read user input in Rust?

2019-03-09 16:09发布

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 make a tokenizer. I need to read every line the user types and stop reading once the user presses ctrl-D.

I searched around and only found one example on Rust IO which does not even compile. I looked at the io module's documentation and found that the read_line() function is part of the ReaderUtil interface, but stdin() returns a Reader instead.

The code that I would like would essentially look like the following in C++

vector<string> readLines () {
    vector<string> allLines;
    string line;

    while (cin >> line) {
        allLines.push_back(line);
    }

    return allLines;
}

标签: input io rust
8条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-09 16:53

As of 17 April 2015 from mdcox on the mozilla rust irc.

use std::io;

fn main() {
    let mut stdin = io::stdin();
    let input = &mut String::new();

    loop {
        input.clear();
        stdin.read_line(input);
        println!("{}", input);
    }
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-03-09 16:58

Editor's note: This answer predates Rust 1.0. Please see the other answers for modern solutions.

In Rust 0.4, use the ReaderUtil trait to access the read_line function. Note that you need to explicitly cast the value to a trait type, eg, reader as io::ReaderUtil

fn main() {
        let mut allLines = ~[];
        let reader = io::stdin();

        while !reader.eof() {
                allLines.push((reader as io::ReaderUtil).read_line());
        }

        for allLines.each |line| {
                io::println(fmt!("%s", *line));
        }
}
查看更多
登录 后发表回答