My example is slightly modified from the guessing game tutorial in The Rust Book.
After the first iteration, the loop does not appear to read in the user input to the mutable string correctly.
Can you please identify what is wrong in the below code with regards to mut input_text?
extern crate rand;
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
let random_number = rand::thread_rng().gen_range(1, 51);
let mut input_text = String::new(); // Works fine if allocated inside loop
loop {
println!("Enter your guess:");
io::stdin()
.read_line(&mut input_text)
.expect("Failed to read input");
let input_number: u32 = match input_text.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!(
"You entered {} which converted to u32 is {}",
input_text, input_number
);
match input_number.cmp(&random_number) {
Ordering::Greater => println!("Input > Random"),
Ordering::Less => println!("Input < Random"),
Ordering::Equal => println!("Input == Random"),
}
}
}
read_line, you append to the existing string. Try callinginput_text.clear()before reading.input_textinside the loop. You noticed yourself that this makes your code work, and the additional allocation really doesn't matter in this case.