Is there a way to check that the user entered an integer with text_io's read!() macro?

两盒软妹~` 提交于 2020-03-05 06:22:06

问题


I want to check that a user entered an integer. If they didn't, I want to redirect them back to the input question:

println!("Place Your Chip");
let mut y_col: usize;

loop {
    y_col = read!();
    // Check if user entered in a integer or not
    if y_col < 1 || y_col > 6 {
        println!("Column space is 1 to 6");
        continue;
    } else {
        y_col -= 1;
    }
    if game.check_column(y_col) {
        println!("\t\t\t\t\t\t\t\tThe column you choose is full");
        continue;
    }
    break;
}

回答1:


The point of read! is to handle errors by killing the thread so that the caller doesn’t need to worry about them. That’s why try_read! exists:

#[macro_use]
extern crate text_io; // 0.1.7

fn main() {
    let mut y_col: Result<usize, _>;

    y_col = try_read!();
    match y_col {
        Ok(v) => println!("Got a number: {}", v),
        Err(e) => eprintln!("Was not a number ({})", e),
    }
}
$ cargo run
123
Got a number: 123

$ cargo run
moo
Was not a number (could not parse moo as target type of __try_read_var__)


来源:https://stackoverflow.com/questions/57501789/is-there-a-way-to-check-that-the-user-entered-an-integer-with-text-ios-read

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!