是否可以在不逐行缓存输入的情况下从 `io::stdin()` 中读取字符? [英] Is it possible to read characters from `io::stdin()` without caching input line-by-line?
问题描述
这个问题指的是稳定的 Rust 版本 1.2.0
我只想遍历 CLI 应用程序标准输入中的字符.完全可以阅读 stdin
的 read_line 方法进入一个临时的 String
实例,然后迭代它的 chars()
迭代器.
但我不喜欢这种方法,因为它分配了一个完全不必要的String
对象.Stdin
trait 的文档实现了 Read
trait, 具有 chars()
迭代器,但它被标记为不稳定(因此不能与稳定的编译器版本一起使用).
是否有另一种可能不太明显的方式来逐个字符读取 stdin,而无需任何额外的 Rust 端缓冲?
你可以通过一个单字节数组来实现,并继续阅读直到 Result
变成一个 Err代码>.但是,这存在一个问题,因为如果您不以 ASCII 字符读取,则可能会出现这种情况.如果您要解决这个问题,最好只分配一个
>String
,并使用 chars
迭代器,因为它可以处理这个问题.
示例代码:
use std::io::{stdin, Read};fn 主(){环形 {让 mut 字符 = [0];而让 Ok(_) = stdin().read(&mut character) {println!("CHAR {:?}", character[0] as char);}}}
示例输出:
Hello WorldCHAR 一些('H')CHAR 一些('e')CHAR Some('l')CHAR Some('l')CHAR 一些('o')CHAR 一些(' ')CHAR 一些('W')CHAR 一些('o')CHAR Some('r')CHAR Some('l')CHAR Some('d')CHAR 一些('\n')你好世界CHAR Some('\u{e4}')CHAR Some('\u{bd}')CHAR Some('\u{a0}')CHAR Some('\u{e5}')CHAR Some('\u{a5}')CHAR Some('\u{bd}')CHAR Some('\u{e4}')CHAR Some('\u{b8}')CHAR Some('\u{96}')CHAR Some('\u{e7}')CHAR Some('\u{95}')CHAR Some('\u{8c}')CHAR 一些('\n')
This question refers to the stable Rust version 1.2.0
I just want to iterate over the characters in the standard input of my CLI application. It's perfectly possible to do read stdin
's read_line method into a temporary String
instance and then iterate over it's chars()
iterator.
But I don't like this approach, as it allocates a totally unnecessary String
object. Stdin
trait's documentations implements Read
trait, which has chars()
iterator, but it is marked as unstable (and thus can't be used with a stable compiler version).
Is there an alternative, possible less obvious way to read stdin char-by-char without any additional Rust-side buffering?
You can do this by having a single byte array, and continuing to read till the Result
becomes an Err
. There is a problem with this however, as this can become if you're not reading in ASCII characters. If you are going to come with up against this problem, it would be better to just allocate a String
, and use the chars
iterator, as it handles this problem.
Sample code:
use std::io::{stdin, Read};
fn main() {
loop {
let mut character = [0];
while let Ok(_) = stdin().read(&mut character) {
println!("CHAR {:?}", character[0] as char);
}
}
}
Sample output:
Hello World
CHAR Some('H')
CHAR Some('e')
CHAR Some('l')
CHAR Some('l')
CHAR Some('o')
CHAR Some(' ')
CHAR Some('W')
CHAR Some('o')
CHAR Some('r')
CHAR Some('l')
CHAR Some('d')
CHAR Some('\n')
你好世界
CHAR Some('\u{e4}')
CHAR Some('\u{bd}')
CHAR Some('\u{a0}')
CHAR Some('\u{e5}')
CHAR Some('\u{a5}')
CHAR Some('\u{bd}')
CHAR Some('\u{e4}')
CHAR Some('\u{b8}')
CHAR Some('\u{96}')
CHAR Some('\u{e7}')
CHAR Some('\u{95}')
CHAR Some('\u{8c}')
CHAR Some('\n')
这篇关于是否可以在不逐行缓存输入的情况下从 `io::stdin()` 中读取字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!