Home
Rust
stdin: Read Line From Console Example
Updated 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.
println
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.
for
if
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.
This page was last updated on Mar 3, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen