0

How to Read Input from Console Examples

Last Updated on

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 3 basic 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 to newline character but this is the default behavior.

Output:

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.

Output:

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.

Output:

Read Console Input Using BufRead.lines

Tested with Rust 1.39.0.

References

Karl San Gabriel

Karl San Gabriel

Professional Software Developer