how to read from stdin rust
To read from stdin in Rust, you can use the std::io
module. Here's an example code snippet that demonstrates how to read input from stdin:
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("Failed to read line");
println!("You entered: {}", input);
}
In this code, we first import the std::io
module. Then, we create a mutable String
variable called input
to store the input we read from stdin.
Next, we use the read_line
method from io::stdin()
to read a line of input from stdin. We pass a mutable reference to the input
variable to store the input we read.
If the read operation is successful, the input will be stored in the input
variable. Otherwise, an error message will be displayed using the expect
method.
Finally, we print out the input using the println!
macro.
You can run this code and test it by entering some input in the console. The program will read the input and display it back to you.