0

The while loop never stops in the following code. I am trying to implement the guessing game in Chapter 2 of the official documentation of Rust. I am new to Rust. Help/explanation will be appreciated.

use std::io;
use rand::Rng;

fn main() {
    println!("Guessing Game");
    println!("Enter guess: ");
    let mut guess = String::new();
    io::stdin().read_line(&mut guess).expect("Failed to read line!");
    println!("You guessed: {}", guess);
    let secret_num = rand::thread_rng().gen_range(1..5);
    while guess != secret_num.to_string() {
        println!("Wrong guess! The correct guess is {}", secret_num);
        println!("\nEnter guess: ");
        guess = String::new();
        io::stdin().read_line(&mut guess).expect("Failed to read line!");
    }
    println!("You guessed the right number: {}", secret_num);
}
heisenbaig
  • 133
  • 6
  • 1
    Does this answer your question? [Why does my string not match when reading user input from stdin?](https://stackoverflow.com/questions/27773313/why-does-my-string-not-match-when-reading-user-input-from-stdin) The `guess` will contain a trailing newline and won't match `secret_num.to_string()`, use [`guess.trim_end()`](https://doc.rust-lang.org/std/primitive.str.html#method.trim_end) – kmdreko Jul 10 '21 at 20:38
  • oh my god thank you so much. it worked. Also, that question is 6 years old and I did not find it useful. – heisenbaig Jul 10 '21 at 20:41

0 Answers0