Search code examples
rustuser-input

User input always true using the .is_ok functions


How can I read from the console and avoid crashing if the user presses enter without entering anything?

let mut objectnumber = String::new();
println!("mennyi súlyt szeretnél megnézni? 3.=255 int");
if io::stdin().read_line(&mut objectnumber).is_ok() {
   println!("{}csdcds", objectnumber);
}

//panic!("{}",objectnumber.len());
if objectnumber.len() < 3 {
   let localrandnum: u8 = thread_rng().gen_range(0..=255);
   println!("miután nem adtál meg semmit sem ezért {localrandnum}.at írtam be neked");
   objectnumber = localrandnum.to_string();
}
let objectnumber: u8 = objectnumber.trim().parse::<u8>().expect("null");

This is working but I don't think it should be done like this in Rust. I don't know why is it ok even on empty line while the parse is talking about it being empty.


Solution

  • Fixes I made:

    • read_line returns a Result indicating whether or not there was an error reading from stdin. Usually this only happens in very specific circumstances, so let's just unwrap this for now.
    • objectnumber.len() gives you the length of the string, not its content. To check its content for < 3, we need to parse() it to a u8 first.
    • Don't expect the parse, because this one depends on user input. Do a proper error handling instead. This is the point that will tell you if the number is >255, <0 or something else entirely. Let's for now just default to '0', because it will then get caught by the < 3.
    • Don't convert the number you generated with the thread_rng to a String; instead, write it to objectnumber directly. There is no point in converting it to a String and back.
    use std::io;
    
    use rand::{thread_rng, Rng};
    
    fn main() {
        let mut objectnumber = String::new();
        println!("mennyi súlyt szeretnél megnézni? 3.=255 int");
        io::stdin()
            .read_line(&mut objectnumber)
            .expect("Unable to read from stdin!");
    
        // Convert from String to u8
        let mut objectnumber: u8 = objectnumber.trim().parse::<u8>().unwrap_or(0);
    
        if objectnumber < 3 {
            objectnumber = thread_rng().gen_range(0..=255);
            println!("miután nem adtál meg semmit sem ezért {objectnumber}.at írtam be neked");
        }
    
        println!("objectnumber: {}", objectnumber);
    }
    
    mennyi súlyt szeretnél megnézni? 3.=255 int
    33
    objectnumber: 33
    
    mennyi súlyt szeretnél megnézni? 3.=255 int
    1
    miután nem adtál meg semmit sem ezért 191.at írtam be neked
    objectnumber: 191