0

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");
    }
}
ilan
  • 17
  • 4
  • At a glance, there's probably a newline in `input_string`. – Caesar Apr 10 '22 at 07:55
  • Have you tried printing the debug representation of the input to see if it differs from what you expected? `println!("Input: {:?}", &input_string);` – Locke Apr 10 '22 at 07:56

1 Answers1

1

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.

at54321
  • 8,726
  • 26
  • 46