Input 如何从输入中读取单个字符作为u8?

Input 如何从输入中读取单个字符作为u8?,input,rust,stdin,Input,Rust,Stdin,我目前正在为练习构建一个简单的口译员。唯一需要解决的问题是从用户输入中读取单个字节作为字符。到目前为止,我有以下代码,但我需要一种方法将第二行生成的字符串转换为u8或另一个可以转换的整数: let input = String::new() let string = std::io::stdin().read_line(&mut input).ok().expect("Failed to read line"); let bytes = string.chars().nth(0) //

我目前正在为练习构建一个简单的口译员。唯一需要解决的问题是从用户输入中读取单个字节作为字符。到目前为止,我有以下代码,但我需要一种方法将第二行生成的
字符串
转换为
u8
或另一个可以转换的整数:

let input = String::new()
let string = std::io::stdin().read_line(&mut input).ok().expect("Failed to read line");
let bytes = string.chars().nth(0) // Turn this to byte?

以字节为单位的值应该是
u8
,我可以将其转换为
i32
,以便在其他地方使用。也许有一种更简单的方法可以做到这一点,否则我将使用任何有效的解决方案。

首先,使输入可变,然后使用
bytes()
而不是
chars()


请注意,Rust字符串是UTF-8代码点序列,不一定是字节大小。根据您试图实现的目标,使用
char
可能是更好的选择。

只读取一个字节并将其强制转换为
i32

use std::io::Read;

let input: Option<i32> = std::io::stdin()
    .bytes() 
    .next()
    .and_then(|result| result.ok())
    .map(|byte| byte as i32);

println!("{:?}", input);
使用std::io::Read;
让输入:Option=std::io::stdin()
.bytes()
.next()
,然后(| result | result.ok())
.map(|字节|字节为i32);
普林顿!(“{:?}”,输入);

我试过这个,但它说需要i32。我在.bytes()上使用了.collect(),但仍然不走运。我认为使用
next()
比使用
nth(0)
更为惯用。虽然它们完全是一样的。@Vladimitmaveev同意,但我已经更改了答案中给出的代码,使其能够正常工作(我忘记了
为i32
cast.dam)。谢谢,我在字符串上使用了.bytes(),遇到了一些问题,但结果证明我用错了。这对我来说很有效,我只需要打开它。这似乎要求在它获取字节之前按Enter键。@AndyHayden stdin通常是行缓冲的。用于更改它。
use std::io::Read;

let input: Option<i32> = std::io::stdin()
    .bytes() 
    .next()
    .and_then(|result| result.ok())
    .map(|byte| byte as i32);

println!("{:?}", input);