1

I would like to ask the user to respond to a question with Y or N. Basically, I have no idea what I'm doing, but here's my attempt anyway

fn ask_confirm(question: &str) -> bool {
    println!("{}",question);
    loop {
        match std::io::stdin().read_u8().map(|x| x as char) {
            Ok('y') | Ok('Y') => return true,
            Ok('n') | Ok('N') => return false,
            Ok(_) => println!("y/n only please."),
            Err(e) => ()
        }
    }
}

This causes an infinite loop. The Err(e) reads "unknown error (OS Error 8 (FormatMessageW() returned error 15105))" on Win 7. Input isn't recognized regardless.

A.B.
  • 15,364
  • 3
  • 61
  • 64
  • What version of Rust are you using? If you are using version 0.9, this maybe fixed on the master branch. You can [experiment using the (newly released) nightly builds](https://mail.mozilla.org/pipermail/rust-dev/2014-March/009223.html). (If you're using master, then... this might be a bug. :( ) – huon Apr 03 '14 at 12:35
  • I'm using a nightly build of 0.10 installed on March 28. I think my code is flawed, what's the proper way to write this function? – A.B. Apr 03 '14 at 12:48
  • 1
    FYI, this is working fine for me with latest Rust from tip on Linux. So I'd suggest filing a bug. – BurntSushi5 Apr 03 '14 at 23:03
  • I filed a bug report as requested. – A.B. Apr 04 '14 at 05:47

1 Answers1

0

I can't find a read_u8 method. I used the logic I answered in this question. Unlike in the previous question since you know that you only want Y, or N this method should work without worry. however input like \sy where \s is space will cause this method to fail.

fn ask_confirm(question: &str) -> bool {
    println!("{}",question);
    loop {
        let mut input = [0];
        let _ = std::io::stdin().read(&mut input);
        match input[0] as char {
            'y' | 'Y' => return true,
            'n' | 'N' => return false,
            _ => println!("y/n only please."),
        }
    }
}
Community
  • 1
  • 1
XAMPPRocky
  • 3,160
  • 5
  • 25
  • 45
  • FWIW, when this question was written (one and a half year ago!), Rust did have `read_uX`/`read_iX` method. Now they are provided in external crates, like `byteorder`. – Vladimir Matveev Sep 13 '15 at 16:01