Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing a string against a string read from input does not match in Rust [duplicate]

Tags:

string

io

rust

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?

like image 237
unskilledidiot Avatar asked Dec 19 '22 15:12

unskilledidiot


1 Answers

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"
like image 79
Shepmaster Avatar answered Dec 26 '22 00:12

Shepmaster