Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Last active April 14, 2022 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/3b5e0d6ed36627060049473382ed2eef to your computer and use it in GitHub Desktop.
Save hnakamur/3b5e0d6ed36627060049473382ed2eef to your computer and use it in GitHub Desktop.
Read a byte from stdin in rust
use std::io;
use std::io::prelude::*;
fn main() -> io::Result<()> {
let mut buffer = [0; 1];
loop {
let n = io::stdin().read(&mut buffer)?;
if n == 0 {
break;
}
print!("{}", std::str::from_utf8(&buffer).unwrap());
}
io::stdout().flush().unwrap();
Ok(())
}
use std::io;
use std::io::prelude::*;
fn main() -> io::Result<()> {
let mut buffer = [0; 1];
loop {
let mut handle = io::stdin().take(1);
let n = handle.read(&mut buffer)?;
if n == 0 {
break;
}
print!("{}", std::str::from_utf8(&buffer).unwrap());
}
io::stdout().flush().unwrap();
Ok(())
}
@hnakamur
Copy link
Author

There may be a better way than this. I'm not a Rust expert.
This assumes only ASCII characters will be feeded from stdin.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment