如何从输入中读取单个字符作为u8? [英] How to read a single character from input as u8?
问题描述
我目前正在为此语言构建一个简单的解释器以进行练习.剩下要克服的唯一问题是从用户输入中读取单个字节作为字符.到目前为止,我有以下代码,但是我需要一种方法将第二行中的String
转换为u8
或我可以转换的另一个整数:
I am currently building a simple interpreter for this language for practice. The only problem left to overcome is reading a single byte as a character from user input. I have the following code so far, but I need a way to turn the String
that the second lines makes into a u8
or another integer that I can cast:
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
以便在其他地方使用.也许有一种更简单的方法可以做到这一点,否则我将使用任何可行的解决方案.
The value in bytes should be a u8
which I can cast to a i32
to use elsewhere. Perhaps there is a simpler way to do this, otherwise I will use any solution that works.
推荐答案
仅读取一个字节并将其强制转换为i32
:
Reading just a byte and casting it to 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);
这篇关于如何从输入中读取单个字符作为u8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!