How to take console input

Hey its 2022 still taking input in rust seems to be quite difficult,
i mean is their any standard and easy method to take input in any format string, integers.

It depends on what you mean by "any" format. If you mean "generically", then the standard library offers both necessary building blocks, using which it is trivial:

use std::error::Error;
use std::str::FromStr;

fn read_stdin<T>() -> Result<T, Box<dyn Error>>
    T: FromStr,
    T::Err: Error + 'static,
    let mut line = String::new();
    std::io::stdin().read_line(&mut line)?;
    let value = line.parse()?;

Of course, reading a string is even simpler: you only need the io::stdin().read_line()? call.

1 Like

I appreciate your response but this is certainly not trivial, Yes I meant console input

What, in particular, is wrong or too complicated about this solution? It only uses std::io::stdin() and FromStr. This is as simple as it gets, as both are needed for a very good and direct reason (stdin for performing the read itself, and FromStr/parse() for converting the string to another type).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.