将字符串与从输入读取的字符串进行比较在Rust中不匹配 [英] Comparing a string against a string read from input does not match in Rust
本文介绍了将字符串与从输入读取的字符串进行比较在Rust中不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的代码中,我希望在用户输入q时打印哇消息,但事实并非如此。
In the following code, I was expecting the message "wow" to be printed when the user enters "q", but it does not.
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input)
.expect("failed to read line");
if input == "q" {
println!("wow") ;
}
}
为什么邮件没有按预期打印?
Why is the message not printed as expected?
推荐答案
您的输入字符串包含一个尾随换行符。使用 trim
将其删除:
Your input string contains a trailing newline. Use trim
to remove it:
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
if input.trim() == "q" {
println!("wow") ;
}
}
您可以通过打印价值来自己看到输入
You could see this yourself by printing the value of the input
println!("{:?}", input);
$ ./foo
q
"q\n"
这篇关于将字符串与从输入读取的字符串进行比较在Rust中不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文