Concept Flow - Reading input basics
Start Program
Prompt User
Read Input Line
Store Input in Variable
Use Input
End Program
The program starts, asks the user for input, reads a line from the keyboard, stores it, then uses it before ending.
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("You typed: {}", input.trim());
}| Step | Action | Input/Value | Variable State | Output |
|---|---|---|---|---|
| 1 | Initialize mutable String variable 'input' | N/A | input = "" | |
| 2 | Prompt user to type input | User sees prompt (implicit) | input = "" | |
| 3 | Read line from stdin into 'input' | User types: Hello Rust! | input = "Hello Rust!\n" | |
| 4 | Trim newline from 'input' | N/A | input = "Hello Rust!\n" | |
| 5 | Print trimmed input | N/A | input = "Hello Rust!\n" | You typed: Hello Rust! |
| 6 | Program ends | N/A | input = "Hello Rust!\n" |
| Variable | Start | After Step 3 | After Step 5 | Final |
|---|---|---|---|---|
| input | "" | "Hello Rust!\n" | "Hello Rust!\n" | "Hello Rust!\n" |
Reading input in Rust:
- Create a mutable String: let mut input = String::new();
- Read line: io::stdin().read_line(&mut input).expect("error");
- Input includes newline, use input.trim() to clean
- Use input as needed
- Program ends after processing inputio::stdin().read_line(&mut input) in Rust?read_lineio::stdin()io::stdin() accesses the standard input stream, allowing the program to receive user input.read_line modifies it.let mut input = String::new(); correctly declares a mutable String variable.use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("You typed: {}", input.trim());
}trim() removes whitespace like newlines.use std::io;
fn main() {
let input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("Input: {}", input);
}read_line requires a mutable reference to modify the string, but input is not mutable.println! syntax are correct; only mutability is missing.i32 in Rust?read_line.trim() to remove whitespace, then parse() to convert to integer, handling errors with expect().Pass the test and this pattern moves unknown