为什么从标准输入读取用户输入时我的字符串不匹配?
我正在尝试获取用户输入并检查用户是否输入“y”或“n”。令人惊讶的是,在下面的代码中,if
和 if else
情况都没有执行!显然,Correct_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!");
}
}
I'm trying to get user input and check if the user put in "y" or "n". Surprisingly, in the below code, neither the if
nor the if else
case executes! Apparently, correct_name
is neither "y" nor "n". How can that be? Am I doing my string conversion wrong or something?
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
在返回的字符串中包含终止换行符。要删除它,请使用
trim_end
甚至更好,只需trim
:最后这个case 处理多种类型的空白:
Windows / Linux / macOS 应该不重要。
您还可以使用修剪结果的长度来截断原始
String
,但在这种情况下,您应该只使用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
在返回的字符串中包含终止换行符。将.trim_right_matches("\r\n")
添加到Correct_name
的定义中以删除终止换行符。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,它提供了chomp
函数 返回没有换行符的字符串切片。还有一个特征
ChompInPlace
< /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.