Standard input, commonly referred to as “stdin”, is a fundamental input stream in most operating systems and is typically associated with the keyboard or other input devices.
In development, “stdin” refers to the input stream that is connected to the running program’s standard input device. Any data from “stdin” is typically read from the user via the keyboard or other input devices.
Reading from “stdin” is a common way to accept the user input or the input from other programs or files. The programs that take an input from “stdin” can be used in pipelines where the output of one program is piped as input to another program.
In this tutorial, we will learn the fundamentals of reading from “stdin” using the Rust programming language.
Requirement:
To understand and follow this tutorial, you will require a Rust development environment and a basic understanding of the Rust programming language.
Project Setup:
Let us setup a basic project using cargo. We can run the command as follows:
Next, edit the “main.rs” file and add the source code as follows:
Read From Stdin
To read from the standard input (stdin) in Rust, we can use the “std::io::stdin” module. An example code is as follows:
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
println!("Your input: {}", input);
}
In the previous example, we use the “std::io” module to read the user input from the terminal. The stdin() function returns a handle to the standard input stream which we can then use to read from.
We create a mutable string variable input to store the input data. We then call the read_line method on the standard input stream, passing in a mutable reference to the input variable.
This method reads the input from the standard input until a newline character (\n) is encountered and appends it to the provided string buffer.
Finally, we print the input using the println! macro.
Note: The newline character at the end of the input is also included in the input.
Your input: hello world
Conclusion
You discovered the most fundamental method of reading the input from the standard input using the Rust programming language.