为什么我的字符串在阅读stdin的用户输入时不匹配?
我正在尝试获取用户输入,并检查用户是否放入“ y”或“ n”。令人惊讶的是,在以下代码中,如果> case case执行!显然, recript_name
既不是“ y”也不是“ n”。那怎么可能?我是在做错了弦转换吗?
use std::io;
fn main() {
let mut correct_name = String::new();
io::stdin().read_line(&mut correct_name).expect("Failed to read line");
if correct_name == "y" {
println!("matched y!");
} else if correct_name == "n" {
println!("matched n!");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
read_line
在返回的字符串中包含终止的newline。要删除它,请使用
trim_end
甚至更好,只需trim
trim :最后一个案例处理许多类型的白期:
Windows / Linux / MacOS不重要。
您也可以使用修剪结果的长度来截断原始的
字符串
,但是在这种情况下,您应仅使用trim_end
!read_line
includes the terminating newline in the returned string.To remove it, use
trim_end
or even better, justtrim
:This last case handles lots of types of whitespace:
Windows / Linux / macOS shouldn't matter.
You could also use the trimmed result's length to truncate the original
String
, but in this case you should only usetrim_end
!read_line
在返回的字符串中包含终止的newline。将.trim_right_matches(“ \ r \ n”)添加到您的定义
recripe_name
以删除终端newline。read_line
includes the terminating newline in the returned string. Add.trim_right_matches("\r\n")
to your definition ofcorrect_name
to remove the terminating newline.您可以使用
chomp-nl
crate 提供字符串切片没有新线字符。还有一个 trait
trait
/a>如果您愿意就位执行此操作。
免责声明:我是这个图书馆的作者。
You can use the
chomp-nl
crate which provides achomp
function which returns a string slice without the newline characters.There is also a trait
ChompInPlace
if you prefer to do this in-place.Disclaimer: I am the author of this library.