Rust:无法将整数解析为字符串,ParseIntError

时间:2019-03-31 06:42:09

标签: string rust integer

我刚刚开始尝试Rust,所以我已经实现了Book的“猜谜游戏”的修改版本。每次我尝试输入数字时,程序都无法从字符串中解析整数:

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)

下面应用了代码。

我已经尝试了其他整数类型。

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);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

read_line输出的字符串包含一个结尾的换行符,因此您需要将其删除以解析该数字。您也可以使用trim_end (or just trim`来处理前导空白):

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