Reading input
- Rust course
- Beginner
- Lesson 61/115
- 6 min
Read the user's guess with std::io::stdin.
Reading input
To read a line from the user, an empty String is created and passed to read_line as &mut. The \n at the end of the line is added to the text too:
let mut tahmin = String::new();
io::stdin()
.read_line(&mut tahmin)
.expect("Satır okunamadı");
println!("Tahminin: {}", tahmin.trim());read_line returns an io::Result<usize> (the number of bytes read); expect stops the program with a message on error.
Why &mut and appending?
read_line appends text; it doesn't overwrite. If you reuse the same String in a loop, call tahmin.clear() every round. In the exercises of these lessons we'll use a fixed text instead of input; the same trim and parse steps apply to real input.
let mut tahmin = String::new();
tahmin.push_str("12\n");
tahmin.clear();
tahmin.push_str("34\n");
println!("{}", tahmin.trim()); // 34Practice Clean the input
Clean the text let girdi = String::from(" 42\n");, which stands for user input, with trim and print it as Tahmin: 42.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let girdi = String::from(" 42\n");
let t = girdi.trim();
println!("Tahmin: {}", t);
}Expected output
Tahmin: 42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If the user types <code>42</code> and presses Enter, what does <code>tahmin</code> contain?
- Empty text
- "42\n" ("42\r\n" on Windows) Correct answer
- The number 42
- "42"
Explanation: read_line appends the line ending too; trim cleans it up.
2 Read the line
let mut tahmin = String::new();
io::stdin()
.read_line(____)
.expect("Satır okunamadı");
let mut tahmin = String::new();
io::stdin()
.read_line(&mut tahmin)
.expect("Satır okunamadı");
Explanation: read_line needs a mutable reference to write the text.
3 Piece and its role
| Term | Meaning |
|---|---|
io::stdin() |
Standard input |
read_line |
Appends a line |
expect |
Stops on error |
trim() |
Removes spaces and \n |