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

发布于 2025-01-16 18:55:18 字数 842 浏览 1 评论 0原文

这是我的代码。它需要一个数字,然后就会出现恐慌。

代码:

//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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对不⑦ 2025-01-23 18:55:18

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

因此,在解析:

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

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:

    let temperatur_int: i32 = temperatur.trim().parse::<i32>().unwrap();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文