gpt4 book ai didi

rust - 如何从 Rust 中的标准输入读取和取消读取 Unicode 字符?

转载 作者:行者123 更新时间:2023-11-29 08:28:48 24 4
gpt4 key购买 nike

在 C 语言中,您使用 getcungetc 来读取字节,并为解析器提供前瞻性。

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

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

最佳答案

在 C 中,getc()ungetc() 使用一个名为 stdin 的全局 FILE *,这允许缓冲输入。在 Rust 中它是相似的,stdin.lock()会给你StdinLock实现Bufread , 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);
}
}

关于rust - 如何从 Rust 中的标准输入读取和取消读取 Unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56618813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com