Search code examples
inputiorust

How can I read user input in Rust?


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;
}

This question refers to parts of Rust that predate Rust 1.0, but the general concept is still valid in Rust 1.0.


Solution

  • 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, for example, 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));
        }
    }
    

    This answer predates Rust 1.0. Please see the other answers for modern solutions.