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

ghz 21days ago ⋅ 23 views

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!");
    }
}

Answer

The issue you're facing is because the input string read from stdin will include the newline character (\n) at the end, which causes the comparison to fail. When the user enters "y" or "n" and presses Enter, the string will actually contain "y\n" or "n\n", which doesn't match exactly with "y" or "n".

To fix this, you need to remove the newline character from the input string using the trim() method before comparing it.

Here's the corrected code:

use std::io;

fn main() {
    let mut correct_name = String::new();
    io::stdin().read_line(&mut correct_name).expect("Failed to read line");
    
    // Trim any leading or trailing whitespace, including the newline character
    let correct_name = correct_name.trim();

    if correct_name == "y" {
        println!("matched y!");
    } else if correct_name == "n" {
        println!("matched n!");
    }
}

Explanation:

  • correct_name.trim() removes leading and trailing whitespace, including the newline character (\n) that gets added when the user presses Enter.
  • By using trim(), the string comparison will now correctly match "y" and "n".

Now, when you enter y or n, it should correctly match and print the corresponding message.