Reading input
- Rust course
- Beginner
- Lesson 26/115
- 6 min
Read number input from the user with std::io::stdin.
Reading input
To read a line from the user, std::io::stdin().read_line is used. The text read, including the trailing newline, is appended to the given String:
use std::io;
let mut girdi = String::new();
io::stdin()
.read_line(&mut girdi)
.expect("okunamadı");
let girdi = girdi.trim(); // "\n" removedread_line returns a Result; expect stops the program with a message if there is an error.
Splitting the input
The input 12 * 3 is split into three pieces with split_whitespace. To keep it testable, we put the parsing in a separate function:
fn parcala(satir: &str) -> Vec<&str> {
satir.split_whitespace().collect()
}
let p = parcala("12 * 3");
println!("{:?}", p); // ["12", "*", "3"]This function can be tried with a string instead of the real stdin.
Practice Parse it
Write the fn parcala(line: &str) -> Vec<&str> function with split_whitespace and collect. Print the result of parcala(" 12 * 3 ") with {:?}.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn parcala(line: &str) -> Vec<&str> {
line.split_whitespace().collect()
}
fn main() {
println!("{:?}", parcala(" 12 * 3 "));
}Expected output
["12", "*", "3"]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does <code>read_line</code> take <code>&mut girdi</code>?
- To write the text read into the existing String Correct answer
- To delete the input
- Because it's faster
- It isn't required
Explanation: The mutable reference lets the function append to the String, so the same buffer can be reused in a loop.
2 Drop the newline
let girdi = girdi.____();
let girdi = girdi.trim();
Explanation: trim removes the newline and spaces read_line leaves.
3 Part and role
| Term | Meaning |
|---|---|
io::stdin() |
Standard input |
read_line |
Reads a line |
expect |
Stops on error |
split_whitespace |
Splits into pieces |