Warm tip: This article is reproduced from stackoverflow.com, please click
conditional-statements rust string user-input

Why does my string not match when reading user input from stdin?

发布于 2020-04-05 00:25:41

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!");
    }
}
Questioner
Joe
Viewed
78
9,873 2015-01-07 02:38

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.