如何在 Rust 中从 stdin 读取和取消读取 Unicode 字符



在 C 中,您可以使用 getcungetc 来读取字节,并提前查看解析器。

在 Rust 中使用 Unicode 字符执行此操作的惯用方法是什么?

我试过io::stdin().chars()但似乎有某种问题,我不明白。编译器抱怨使用它。

在 C 中,getc()ungetc() 正在使用名为 stdin 的全局FILE *,这允许缓冲输入。在 rust 中它是类似的,stdin.lock()会给你实现Bufread StdinLock,AFAIK 没有内置的方法可以做你想做的事,人们只会使用lines().此外,你的要求比看起来更难,你要求 unicode 流,而你的 C 函数不关心这个。

所以这里有一个基本的解决方案:

use std::io;
use std::io::prelude::*;
use std::str;
fn main() {
    let stdin = io::stdin();
    let mut stdin = stdin.lock();
    while let Ok(buffer) = stdin.fill_buf() {
        let (input, to_consume) = match str::from_utf8(buffer) {
            Ok(input) => (input, input.len()),
            Err(e) => {
                let to_consume = e.valid_up_to();
                if to_consume == 0 {
                    break;
                }
                let input = unsafe { str::from_utf8_unchecked(&buffer[..to_consume]) };
                (input, to_consume)
            }
        };
        println!("{}", input);
        // here you could do many thing like .chars()
        stdin.consume(to_consume);
    }
}

最新更新