# Handling Bad Input

Here's our current code:

{% code title="main.rs" %}

```rust
use std::io;
use std::cmp::Ordering;

fn main() {
    println!("Guess the number!");

    let secret_number = 42;

    println!("The secret number is: {}", secret_number);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin().read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = guess.trim().parse()
            .expect("Please type a number!");

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            },
        }
    }
}
```

{% endcode %}

What's the problem now? Well, right now, if you enter something that is non-numeric, you get an error and it stops the program. Let's handle that!

```rust
let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => continue,
};
```

Just like we are doing when we compare the guess, we can also use `match` on the results of `parse`, which only has two varients. We use the `_` because we don't care what the content of `Err` is, we just want to continue.

What if we do want to output the content of `Err`? Let's change the code again to print out the message.

```rust
let guess: u32 = match guess.trim().parse() {
              Ok(num) => num,
              Err(msg) => {
                println!("{}", msg);
                continue;
              },
          };
```

Here's what the output looks like now:

![](/files/-LBqOxXkzjHe6XcMaeey)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jmkoni.gitbook.io/rust/guessing-game/handling-bad-input.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
