How to read a single character from input as u8?

后端 未结 2 1669
误落风尘
误落风尘 2021-01-17 13:56

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 hav

2条回答
  •  情歌与酒
    2021-01-17 14:57

    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.

提交回复
热议问题