7

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
unskilledidiot
  • 689
  • 1
  • 6
  • 11

1 Answers1

24

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"
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366