Search code examples
if-statementruststdin

Why doesn't this print nomatter what I input?


I am new to rust and just learned about user input from the command line, I tried making this simple program to test out. When I run it I don't get any errors but even if I put in "mac" or anything else it doesn't print anything. I would like to understand why this happens, if anyone can explain that I would appreciate it a lot.

here is my code:

use std::io::{stdin, stdout, Write};

fn main() {
    print!("State your OS: ");
    stdout().flush().expect("Flush Failed!");
    let mut input_string = String::new();
    stdin()
        .read_line(&mut input_string)
        .ok()
        .expect("Failed to read line!");
    if input_string == "mac" {
        println!("Mac");
    } else if input_string == "windows" {
        println!("Windows");
    } else if input_string == "linux" {
        println!("Linux");
    }
}

Solution

  • Your input string has a newline character at the end. This is specified in the documentation of read_line().

    One possible solution to your problem would be to trim the string. Example:

    use std::io::{stdin, stdout, Write};
    
    fn main() {
        print!("State your OS: ");
        stdout().flush().expect("Flush Failed!");
        let mut input_string = String::new();
        stdin()
            .read_line(&mut input_string)
            .ok()
            .expect("Failed to read line!");
        let s = input_string.trim();    
        if s == "mac" {
            println!("Mac");
        } else if s == "windows" {
            println!("Windows");
        } else if s == "linux" {
            println!("Linux");
        }
    }
    

    There are other possible approaches to this, but I think in almost all cases it's a good practice to trim() the user input. Note that your user could potentially enter " mac", in which case you would probably want to treat the input as "mac" anyway.