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

ogsagwnx  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(80)

此问题在此处已有答案

Why does my string not match when reading user input from stdin?(3个答案)
7天前关闭
我对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:

sdnqo3pr

sdnqo3pr1#

您的字符串包含用户输入的\n。试试这个

let unit = temp.trim().chars().last().unwrap();

字符串

相关问题