Complete the code to read a line of input from the user.
use std::io;
fn main() {
let mut input = String::new();
io::stdin().[1](&mut input).expect("Failed to read line");
println!("You typed: {}", input.trim());
}The read_line method reads a line from standard input into the provided string buffer.
Complete the code to convert the input string to an integer.
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let num: i32 = input.trim().[1]().expect("Please type a number!");
println!("You typed the number: {}", num);
}The parse method converts a string slice into a number type, here i32.
Fix the error in the code to correctly handle input and parse it as a floating-point number.
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let num: f64 = input.[1]().expect("Please type a number!");
println!("You typed the number: {}", num);
}You must call trim() before parse() to remove whitespace and newline characters.
Fill both blanks to read input, trim it, and parse it as an unsigned integer.
use std::io;
fn main() {
let mut input = String::new();
io::stdin().[1](&mut input).expect("Failed to read line");
let num: u32 = input.[2]().parse().expect("Please type a number!");
println!("Number: {}", num);
}First, use read_line to get input. Then trim removes whitespace before parsing.
Fill all three blanks to read input, trim it, parse it as i64, and handle possible errors.
use std::io;
fn main() {
let mut input = String::new();
io::stdin().[1](&mut input).expect("Failed to read line");
let trimmed = input.[2]();
let num: i64 = match trimmed.parse() {
Ok(n) => n,
Err(_) => {
println!("Invalid number");
return;
}
};
println!("You typed: {}", num);
}Use read_line to get input, trim to clean it, and parse to convert to a number with error handling.