Rust, Software Development

How to Read Input from Console Examples

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.


Input with Newline Character

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.


Read Console Input with no Newline Character

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.


Read Console Input Using BufRead.lines

Tested with Rust 1.39.0.



Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like