Convert user input to Numeral

Convert user input to Numeral

Input to Numeral

This method is useful when the expected input will contain a simple number.

If you have to parse the sentence for the number, this is not the method you should be using.

let mut num1 = String::new();

println!("What is the first number? ");
stdin().read_line(&mut num1).expect("Invalid input");

let num1: i32 = num1.trim().parse::<i32>().expect("We're expecting a number");

println!("The number you typed was {}", num1);
What is the first Number?
The number you typed was 42


Note that when you try to parse the number into an i32 Numeral it will panic if what you typed cannot be parsed!

Leave your opinion, start a discussion, share an experience or just a compliment...

%d bloggers like this: