为初学者解决 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
this is my code. It takes a number and then panicks.
Code:
//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);
}
Error:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在做正确的事情,但您忘记了从标准输入读取时会在字符串中得到换行符。因此,您将得到的是无法解析的“32\n”,而不是“32”。
因此,在解析:
You're doing the right thing, but you forgot that you will get a newline in your string when reading from stdin. So instead of '32' you will have '32\n', which cannot be parsed.
So do trim() additionally before the parsing: