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);
            }
        }
    }
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
rustafarian
  • 39
  • 1
  • 3
  • The result of `read_line` includes the `'\n'` character, which is causing the parse error. – Peter Hall Mar 31 '19 at 06:59
  • 1
    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. – Peter Hall Mar 31 '19 at 10:47
  • Does fs:: read_string also do the same, like includes the \n character ? I was reading from this file https://adventofcode.com/2020/day/1/input – Aritro Shome Jun 12 '21 at 06:20

1 Answers1

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!");
Peter Hall
  • 53,120
  • 14
  • 139
  • 204