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!");
}
}
read_line
includes the terminating newline in the returned string. Add .trim_right_matches("\r\n")
to your definition of correct_name
to remove the terminating newline.
What about Windows, should it be "\r\n"?
It tells me bool` is not implemented for the type `&str when I add that
I realized it has to go in the if statement after I looked at docs. Thanks!
You should not need
as_slice
, sinceString
implementsDeref<Target=str>
.let line = io::stdin().read_line(); let trimmed = line.trim_right_chars(..);
should work.And I'd suggest using just
trim
ortrim_right
instead of trying to worry about cross-platform newlines :-)