Greetings,
I am trying to get user input expecting floating point number and show error prompt using match
until number(s) being used. I also want to catch the floating value outside the loop to use for calculation.
I used stdin
to get user input and stored in a value
variable created from String::new()
. Because value
stored input from user, it was String type. I used value.trim().parse::<f32>()
to convert it into f32
type. It seems i am doing something wrong.
During compile time i get mismatched type error.
It says: expected f32 found String
Here is my code:
fn main() {
println!("\nPlease Input the Value you want to convert: ");
let value:f32 = loop{
let mut value = String::new();
std::io::stdin()
.read_line(&mut value)
.expect("Failed to read line");
match value.trim().parse::<f32>(){
Ok(num) => break value, //edited: mistake was here, should be num not value.Thanks to H2CO3
Err(_) => {
println!("please input value in number(s).");}
};
};
println!("Thank You, I have the value: {value}.")
}