In Rust, we can read user inputs from the command-line console. These inputs are string values with newline characters at the end. Most of the time, we do not want those extra characters. This post provides three simple example codes that read user input data from the command-line console.
Example 1 – Input with Newline Character
Consider this first example. The following codes read the input string plus the newline character when a user inputs a text and presses the enter key. Most of the time, we do not want a newline character, but this is the default behavior.
1 2 3 4 5 6 7 8 9 10 | use std::io; fn main() { println!("Enter your name: "); let mut name = String::new(); io::stdin().read_line(&mut name).expect("Failed to read line"); println!(); println!("Hello {}!", name); } |
Output:
Example 2 – Read Console Input with no Newline Character
Given the example above, most people will resort to stripping the newline character from the input string.
1 2 3 4 5 6 7 8 9 10 11 | use std::io; fn main() { println!("Enter your name: "); let mut name = String::new(); io::stdin().read_line(&mut name).expect("Failed to read line"); println!(); // Strip off the last character println!("Hello {}!", &name[..name.len()-1]); } |
Output:
Example 3 – Read Console Input Using BufRead.lines()
This last example will read user input using BufRead.lines(), which creates an iterator.
A BufRead is a type of Reader which has an internal buffer, allowing it to perform extra ways of reading.
For example, reading line-by-line is inefficient without using a buffer, so if you want to read by line, you’ll need BufRead, which includes a read_line method as well as a lines iterator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | use std::io; use std::io::BufRead; fn main() { println!("Enter your name: "); let mut name = String::new(); name = io::stdin().lock().lines().next().unwrap().unwrap(); println!("Enter your age: "); let mut age = String::new(); age = io::stdin().lock().lines().next().unwrap().unwrap(); println!(); println!("Hello {} who is {} years old!", name, age); } |
Output:
Tested with Rust 1.39.0.
References