Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Process quitting in Rust

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);
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading