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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.