为初学者解决Rust中的parse()错误



这是我的代码。这需要一个数字,然后恐慌。

代码:

//Convert temperatures between Fahrenheit and Celsius.
use std::io;
fn main() {
let c: bool = true;

let f: bool = false;
let mut temperatur = String::new();

println!("Gib die Temperatur an:");

io::stdin()
.read_line(&mut temperatur)
.expect("Konnte nicht gelesen werden");

let temperatur_int: i32 = temperatur.parse::<i32>().unwrap();

println!("{}", temperatur_int);
}

错误:

Gib die Temperatur an: 5 thread 'main' panicked at 'called Result::unwrap()on anErrvalue: ParseIntError { kind: InvalidDigit }', src/main.rs:17:57 note: run withRUST_BACKTRACE=1 environment variable to display a backtrace
Tried to parse String to Integer

您正在做正确的事情,但您忘记了从stdin读取时会在字符串中得到一个换行符。因此,您将得到无法解析的"32 \n",而不是"32"。

因此,在解析之前额外执行trim((:

let temperatur_int: i32 = temperatur.trim().parse::<i32>().unwrap();

最新更新