How to take multiple inputs from standard in in Rust?

随声附和 提交于 2021-01-29 14:05:05

问题


I want to take 2 user inputs, height and width:

fn main() {
    let mut w = String::new();
    let mut l = String::new();
    println!("Enter the width");
    io::stdin().read_line(&mut w).expect("failed to read input");
    let w: i32 = w.trim().parse().expect("invalid input");

    println!("Enter the length");
    io::stdin().read_line(&mut l).expect("failed to read input");
    let l: i32 = l.trim().parse().expect("invalid input");

    println!("width {:?}", w);
    println!("length{:?}", l);
}

Is there a shorter way to achieve this?


回答1:


Handling input from the terminal is not really fun, so a number of crates try to make is shorter/easier/more luxurious.

A possible candidate is rprompt:

let reply = rprompt::prompt_reply_stdout("Password: ").unwrap();
println!("Your reply is {}", reply);

That is probably just a shortcut to Thomas' advice of wrapping all that stuff in a function of your own. I prefer using crates because they allow for nice little features like enabling the user to correct their input when they made a mistake...

prompty may be worth looking at.




回答2:


An idiomatic way to provide user input is to entirely avoid quizzing the user. Instead, accept short inputs through command-line arguments and long inputs through files or the standard input. In this case you can use clap to parse the command line:

#[macro_use]
extern crate clap;

use clap::{App, Arg};

fn main() {
    let matches = App::new("My Program")
        .arg(Arg::with_name("width").required(true))
        .arg(Arg::with_name("height").required(true))
        .get_matches();

    let width = value_t!(matches, "width", i32).unwrap();
    let height = value_t!(matches, "height", i32).unwrap();

    println!("{} {}", width, height);
}

This will allow you to invoke the program as my_program 10 20, to edit the invocation using advanced shell editing facilities, remember it in shell history, or automate it with scripts.

Compared to requiring the user to type in the values over and over for each invocation, without readline or history, it's more user-friendly, more professional, and it matches the best practices of the ecosystem.



来源:https://stackoverflow.com/questions/63580989/how-to-take-multiple-inputs-from-standard-in-in-rust

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