Rust Tutorials: Reading from stdin

beginner
22 min

Rust Tutorials: Reading from stdin

Welcome to the Reading from stdin tutorial! This lesson is part of our Rust series, designed for both beginners and intermediate learners. By the end of this tutorial, you'll be able to read input from the user using Rust. Let's get started! šŸŽÆ

Understanding stdin

In Rust, stdin is a standard input stream. It allows you to read input from the user's keyboard.

rust
use std::io; // Import the io module for input/output operations fn main() { let mut input = String::new(); // Create a mutable String to store user input println!("Enter something:"); // Print a message asking the user for input io::stdin() // Get a reference to stdin .read_line(&mut input) // Read a line of input into the `input` string .expect("Error reading input"); // Handle any potential errors println!("You entered: {}", input); // Print the user's input }

šŸ’” Pro Tip: In the code above, we import the io module to perform input and output operations. We create a mutable String called input to store the user's input. The read_line function is used to read a line of input, and the expect function is used to handle potential errors.

Reading and storing multiple lines of input

If you want to read and store multiple lines of input, you can modify the code like this:

rust
use std::io; fn main() { let mut lines = Vec::new(); // Create a mutable Vector to store the lines of input println!("Enter some lines. Type 'quit' to finish."); loop { let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("Error reading input"); if input.trim() == "quit" { break; } lines.push(input); // Add the line to the Vector } println!("You entered:"); for line in lines { println!(" - {}", line); } }

šŸ’” Pro Tip: In the code above, we use a loop to continuously read input until the user types "quit". We store each line of input in a Vector called lines. To get the trimmed version of the input, we use the trim function to remove any leading and trailing whitespace.

Quiz

Quick Quiz
Question 1 of 1

What does `stdin` refer to in Rust?

That's it for this lesson! In the next lesson, we'll learn how to write to stdout and create more interactive applications. Happy coding! šŸ“