如何在Rust中阅读用户输入? [英] How can I read user input in Rust?

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

问题描述

我打算做一个标记器.我需要阅读用户键入的每一行,并在用户按下 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.

我到处搜索,仅找到一个示例在什至无法编译的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早于Rust 1.0的部分,但一般概念在Rust 1.0中仍然有效.

推荐答案

在Rust 0.4中,使用 ReaderUtil 特性访问 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, 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));
    }
}

此答案早于Rust 1.0.请参阅有关现代解决方案的其他答案.

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

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