Rust Program to read Integer input from User

Rust-Programs

In this article, we are going to learn about a simple Rust Program to read Integer input from User. We will ask the user to enter the desired input as an integer, then we will validate if the user entered an Integer value or something else.

1. Rust Program to read Integer input from User


use std::{
    io::{
        self,
        Write,
    },
    process,
};

fn main() {
    println!("- Please enter an integer Value: ");
    
    io::stdout().flush().unwrap();

    let mut input = String::new();

    io::stdin().read_line(&mut input).unwrap();

    let user_input = input.trim().parse::<i32>().unwrap_or_else(|_| {
        eprintln!("- Entered input is not Integer!");
        drop(input);
        process::exit(1);
    });

    println!(
        "- The input entered by User is {}.",
        user_input,
    );

Output

 rustc -o main main.rs
 ./main
- Please enter an integer Value: 
12
- The input entered by User is 12.

 rustc -o main main.rs
 ./main
- Please enter an integer Value: 
abc
- Entered input is not Integer!
exit status 1

2. Rust Program for how to read Integer input from the standard input console


use std::{
    io::{
        self,
        Write,
    },
    process,
};

fn main() {
    println!("- Please enter a Floating(Decimal) or Integer Value: ");
    
    io::stdout().flush().unwrap();

    let mut input = String::new();

    io::stdin().read_line(&mut input).unwrap();

    let user_input = input.trim().parse::<f32>().unwrap_or_else(|_| {
        eprintln!("- Entered input is neither Integer nor Float!");
        drop(input);
        process::exit(1);
    });

    println!(
        "- The input entered by User is {}.",
        user_input,
    );
}

Output

 rustc -o main main.rs
 ./main
- Please enter a Floating(Decimal) or Integer Value: 
12.55
- The input entered by User is 12.55.



rustc -o main main.rs
./main
- Please enter a Floating(Decimal) or Integer Value: 
abc
- Entered input is neither Integer nor Float!
exit status 1