2015-06-06 22 views
8

我目前正在为练习编译this language。要克服的唯一问题是从用户输入中读取单个字节作为字符。我有以下的代码,到目前为止,但我需要一种方法来转String第二行打造成为一个u8或另一个整数,我可以投:如何从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以在别处使用。也许有一个更简单的方法来做到这一点,否则我会使用任何有效的解决方案。

回答

9

阅读只是一个字节,它铸造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); 
+0

谢谢,我在字符串上使用了.bytes()并出现问题,但事实证明我错误地使用了它。这对我有用,我只需要打开它。 – pengowen123

2

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

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

请注意Rust字符串是UTF-8码点序列,它们不一定是字节大小的。根据你想要达到的目标,使用char可能是更好的选择。

+0

我想这一点,但它说,它需要一个123-132。我在.bytes()上使用了.collect(),但仍然没有运气。 – pengowen123

+0

我认为使用'next()'而不是'n(0)'更加通俗。虽然他们是完全一样的东西。 –

+0

@VladimirMatveev同意,我改变了答案中给出的代码就足以使它工作(我忘了'因为i32'投了,该死的)。 – llogiq

相关问题