用户输入字符串的最后一个字符不正确[重复]

问题描述 投票:0回答:1

我对 Rust 很陌生,我正在尝试从用户输入中获取字符串的最后一个值。我尝试实现它,但它没有给出预期的输出

    println!("Please input temp (ex: 60F): ");
    let mut temp = String::new();
    io::stdin()
        .read_line(&mut temp)
        .expect("Failed to read line");
    println!("{temp}");
    let unit = temp.chars().last().unwrap();
    println!("unit: {}", unit);

非常感谢提供的任何帮助!

我尝试了 stackoverflow 和 reddit 的多种解决方案,但效果不佳。

机器的预期输出应类似于:

> Please input temp (ex: 60F): 
60f
unit: f

但我得到的输出是:

> Please input temp (ex: 60F): 
60f
unit: 
string rust char
1个回答
0
投票

您的字符串包含用户输入的

\n
。试试这个

let unit = temp.trim().chars().last().unwrap();
© www.soinside.com 2019 - 2024. All rights reserved.