Rust Program to read the integer from user input 3 variations
Program
use std::io;
fn main()
{
let mut n = String::new();
println!("Demonstrating three types of reading an integer input from the user");
println!("Enter an integer value: ");
io::stdin().read_line(&mut n).expect("failed to read input.");
let n: i32 = n.trim().parse().expect("invalid input");
println!("Type 1 : User entered value is {:?}", n);
println!("Enter an integer value: ");
let mut n = String::new();
io::stdin().read_line(&mut n).expect("failed to read input.");
let n = n.trim().parse::<i32>().expect("invalid input");
println!("Type 2: User entered value is {:?}", n);
println!("Enter an integer value:");
let mut n = String::new();
io::stdin().read_line(&mut n).expect("failed to read input.");
if let Ok(n) = n.trim().parse::<i32>() {
println!("Type 3: User entered value is {:?}", n);
}
}
Output
$ rustc ReadIntegerPrint.rs
$ ./ReadIntegerPrint
Demonstrating three types of reading an integer input from the user
Enter an integer value:
56
Type 1 : User entered value is 56
Enter an integer value:
89
Type 2: User entered value is 89
Enter an integer value:
123
Type 3: User entered value is 123