2

I just started to experiment with Rust, so I've implemented modified version from Book's "Guessing game". Every first time I'm trying to enter the number, program fails to parse integer from string:

Guess the number!
Input your guess:
50
You guessed 50
 (4 bytes)!
thread 'main' panicked at 'Wrong number format!: ParseIntError { kind: InvalidDigit }', src\libcore\result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
error: process didn't exit successfully: `target\release\experiment.exe` (exit code: 101)

Code applied below.

I already tried other integer types.

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

fn main() {
    println!("Guess the number!\nInput your guess:");

    let mut guess = String::new();

    let secnum = rand::thread_rng().gen_range(1,101);

    'br: loop { 
        match io::stdin().read_line(&mut guess) {
            Ok(okay) => {
                println!("You guessed {} ({} bytes)!", guess, okay);

                let intguess = guess.parse::<u8>()
                    .expect("Wrong number format!");

                match secnum.cmp(&intguess) {
                    std::cmp::Ordering::Less => {
                        println!("Your guess is smaller!");
                    }
                    std::cmp::Ordering::Greater => {
                        println!("Your guess is bigger!");
                    }
                    std::cmp::Ordering::Equal => {
                        println!("You guessed right!");
                        break 'br;
                    } 
                }
            }
            Err(erro) => {
                println!("Failed to read the line: {}!", erro);
            }
        }
    }
}
3
  • The result of read_line includes the '\n' character, which is causing the parse error. Commented Mar 31, 2019 at 6:59
  • 3
    You can just call string.clear() to reuse the same string. In this kind of IO code, there is really very little impact to allocating a new String each time though. Commented Mar 31, 2019 at 10:47
  • Does fs:: read_string also do the same, like includes the \n character ? I was reading from this file adventofcode.com/2020/day/1/input Commented Jun 12, 2021 at 6:20

1 Answer 1

7

The string output from read_line includes a trailing newline character, so you will need to strip that out in order to parse the number. You can do that with trim_end (or just trim to handle leading whitespace too):

let guess: u8 = guess
    .trim_end()
    .parse()
    .expect("Wrong number format!");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.