You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何读取用户输入字符串的最后字符结果不符合预期?

问题原因

read_line方法会把用户输入时按下的换行符(Unix下是\n,Windows下是\r\n)也一并读取到字符串里。你输入60f回车后,temp的实际内容是"60f\n",所以调用chars().last()拿到的是换行符,输出自然是空行。

解决方案

这里提供几种可行的处理方式:

方法1:移除末尾所有空白字符(推荐)

用trim_end()去掉字符串末尾的空白(包括换行、空格、制表符等),再取最后一个字符:

println!("Please input temp (ex: 60F): ");
let mut temp = String::new();
io::stdin()
    .read_line(&mut temp)
    .expect("Failed to read line");
// 移除末尾空白
let trimmed_temp = temp.trim_end();
let unit = trimmed_temp.chars().last().unwrap();
println!("unit: {}", unit);

方法2:精准移除换行符

如果你只想去掉换行符,保留其他末尾空白,可以手动判断并移除:

println!("Please input temp (ex: 60F): ");
let mut temp = String::new();
io::stdin()
    .read_line(&mut temp)
    .expect("Failed to read line");
// 处理Unix和Windows的换行符
if temp.ends_with('\n') {
    temp.pop();
    if temp.ends_with('\r') {
        temp.pop();
    }
}
let unit = temp.chars().last().unwrap();
println!("unit: {}", unit);

方法3:移除前后所有空白

如果你的输入不会有前后多余空格,也可以用trim()去掉字符串首尾的所有空白:

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

内容的提问来源于stack exchange,提问作者Wei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 04:46:04