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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With