Stdin. Some console programs can benefit from being interactive—when the user types a string, they print a message. This can be done with the stdin function in Rust.
Tip To ensure the line data is as easy to process as possible, we can call trim_end to remove trailing newlines (and spaces).
use std::io;
fn main() {
// Read in input.
let mut buffer = String::new();
let stdin = io::stdin();
while stdin.read_line(&mut buffer).is_ok() {
// Trim end.
let trimmed = buffer.trim_end();
println!("You typed: [{trimmed}]");
buffer.clear();
}
}test
You typed: [test]
hello
You typed: [hello]
friend
You typed: [friend]
Discussion. In my experience, having a command-line program that does one thing and exits is the easiest approach. This allows it to be called from other programs more easily.
However For some types of programs an interactive command line parser can be a better experience. Try stdin and find out.
A summary. We read lines from the command line in an interactive Rust program, and trimmed the end of the strings. A program could run certain functions based on typed input.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.