Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a single character from input as u8?

Tags:

input

stdin

rust

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?

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.

like image 877
pengowen123 Avatar asked Jun 06 '15 04:06

pengowen123


2 Answers

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);
like image 52
A.B. Avatar answered Nov 04 '22 13:11

A.B.


First, make your input mutable, then use bytes() instead of 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");

Please note that Rust strings are a sequence of UTF-8 codepoints, which are not necessarily byte-sized. Depending on what you are trying to achieve, using a char may be the better option.

like image 31
llogiq Avatar answered Nov 04 '22 12:11

llogiq