stdin: Read Line From Console Example
This page was last reviewed on Mar 3, 2023.
Dot Net Perls
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.
By calling read_line in a loop, we can keep accessing the data typed by the user. But to get the line we have to clear the buffer of data.
An example. To begin, we need to include the std io module—this includes the stdin() function that we need to call. We create a buffer string.
Info In Rust, Strings have growable buffers, so they can be used as a buffering type. They optimize out allocations.
Here We call read_line on stdin in a while loop. Read_line returns a Result, so we call is_ok() to ensure we get something.
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.
This page was last updated on Mar 3, 2023 (edit).
© 2007-2024 Sam Allen.