Comparing a string against a string read from inpu

2019-05-30 19:15发布

问题:

This question already has an answer here:

  • Why doesn't my user input from stdin match correctly? 3 answers

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?

回答1:

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"


标签: string io rust