Search code examples
inputruststring-comparison

How can I compare a user input to a specific char?


I want to compare a user input to specific char in Rust. For example I would print something like: "Press "q" to quit" and the user should enter the letter "q" and press Enter to exit the program. If the input is longer than 1 character, the program should print something like: "not valid". I discovered that on Linux the actual input looks like this: "q\n" and on windows like this: "q\r\n" so I ended up with the following code:

println!("Enter "q" to quit");

let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read input");

let input_bytes = input.as_bytes()[0];
let quit: [u8; 1] = *b"q";

if input_bytes.eq(&quit[0]) {
    std::process::exit(0);
}

to read only the first byte. It works but it doesn`t check the length of the input. So anything starting with "q" will do the job.

I couldn`t find a solution on this and I am searching for days now. Maybe I am asking the wrong questions on the search engines. I am not an expert and thankful for help.


Solution

  • You should first trim your string to remove the whitespace, and compare the entire thing, instead of just grabbing the first byte. A match or if statement can then decide how your program should continue, depending on the input.

    fn main() {
        println!("Enter \"q\" to quit");
    
        loop {
            let mut input = String::new();
            std::io::stdin().read_line(&mut input).expect("Failed to read input");
    
            match input.trim() {
                "q" => std::process::exit(0),
                _ => println!("keep going"),
            }
        }
    }