Read a single line from stdin
:
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
You may remove '\n'
using line.trim_end()
Read until EOF:
let mut buffer = String::new();
std::io::stdin().read_to_string(&mut buffer)?;
Using implicit synchronization:
use std::io;
fn main() -> io::Result<()> {
let mut line = String::new();
io::stdin().read_line(&mut line)?;
println!("You entered: {}", line);
Ok(())
}
Using explicit synchronization:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let mut handle = stdin.lock();
let mut line = String::new();
handle.read_line(&mut line)?;
println!("You entered: {}", line);
Ok(())
}
If you interested in the number of bytes e.g. n
, use:
let n = handle.read_line(&mut line)?;
or
let n = io::stdin().read_line(&mut line)?;
Try this:
use std::io;
fn main() -> io::Result<()> {
let mut line = String::new();
let n = io::stdin().read_line(&mut line)?;
println!("{} bytes read", n);
println!("You entered: {}", line);
Ok(())
}
See doc