如何在Rust中读取用户输入? [英] How to read user input in Rust?

查看:1105
本文介绍了如何在Rust中读取用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


编者注:这个问题是指在Rust 1.0之前的Rust部分,但是一般概念在Rust 1.0中仍然有效。

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.

我打算制作一个标记器。我需要读取用户键入的每一行,并在用户按下 ctrl - D 后停止阅读。

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搜索过,只找到了关于Rust的一个例子 IO甚至没有编译。我查看了 io 模块的文档,发现 read_line()函数是 ReaderUtil 接口,但 stdin()返回 Reader

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.

我想要的代码在C ++中基本上如下所示

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


推荐答案


编者注:这个答案早于Rust 1.0。请参阅现代解决方案的其他答案。

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

在Rust 0.4中,使用 ReaderUtil trait访问 read_line 函数。请注意,您需要将值显式转换为特征类型,例如, reader as io :: ReaderUtil

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

这篇关于如何在Rust中读取用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆