Advertisements
I decided to make an application that will find the median of any given list of numbers.
I wanted to make an option to quit the process, but when I tested it, the process keeps going.
Whenever I type "q" it should stop, however it does not.
use std::io;
fn main() {
let mut v1: Vec<i32> = Vec::new();
loop {
println!("Enter: ");
let mut inp: String = String::new();
io::stdin().read_line(&mut inp).expect("Failure");
let upd_inp: i32 = match inp.trim().parse() {
Ok(num) => num,
Err(_) => if inp == String::from("q") {
break
} else {
continue
}
};
v1.push(upd_inp);
println!("{:?}", v1);
}
}
>Solution :
str::trim
doesn’t modify the string. It returns a slice of the string (basically, a substring). So even though you did inp.trim()
on an earlier line, the inp
being compared in your if
statement still has a newline at the end. Simply change your comparison to
inp.trim() == String::from("q")
and the input of q
will be detected as intended.