I am trying to read in bytes from standard input in Rust. The code below works perfectly for lines consisting of regular characters, but for raw bytes that don't have associated characters (such as 0xe0
), this causes the program to panic. The documentation says that it will terminate at the newline character, but doesn't mention any issues with non-character bytes.
EDIT: I actually missed that it does say that all bytes must be UTF-8 encoded- is there another function I can use to do this?
let mut input = String::new();
io::stdin().read_line(&mut input)
.ok()
.expect("Couldn't read line");
It turns out that Stdin implements the Read trait, so I was able to use the bytes method:
for i in io::stdin().bytes() {
println!("read byte {}", i.unwrap());
}
And this loop can be broken out of by checking each byte until it's the desired byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With