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

ogsagwnx  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(127)

此问题在此处已有答案

Why does my string not match when reading user input from stdin?(3个答案)
7天前关闭
我对Rust很陌生,我试图从用户输入中获取字符串的最后一个值。我尝试实现它,但它没有给予预期的输出。

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

字符串
将感谢提供任何帮助!
我尝试了stackoverflow和reddit的多种解决方案,但效果不佳。
机器的预期输出应该是这样的:

  1. > Please input temp (ex: 60F):
  2. 60f
  3. unit: f


但我得到的输出是:

  1. > Please input temp (ex: 60F):
  2. 60f
  3. unit:

sdnqo3pr

sdnqo3pr1#

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

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

字符串

相关问题