在C语言中,您使用getc
和ungetc
读取字节,以预见解析器。
在Rust中使用Unicode字符的惯用方式是什么?
我尝试了io::stdin().chars()
,但似乎有些问题,我不明白。编译器抱怨使用它。
答案 0 :(得分:1)
在C中,getc()
和ungetc()
使用名为FILE *
的全局stdin
,这样就可以缓冲输入。生锈的情况类似,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);
}
}