Using break in looping

I can't get out of the loop, I have to force it with ctrl+c. Is the break correct? When reading "exit", the program must stop, otherwise it checks for an even or odd number.

use std::io;

fn main() {
    loop {
        println!("Check whether a number is even or odd.");
        println!("Enter an integer or type "exit" to exit: ");
        let mut x = String::new();
        io::stdin().read_line(&mut x).expect("Failed to read input");
        println!("Você digitou {}!", x);
        if x == "exit" {
            break;
        }
        else {
            let mut x: u32 = match x.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
            };
            x = x % 2;
            if x == 0 {
    println!("The number is EVEN");
    } else {
      println!("The number is ODD");
      }
   }
 }
}

read_line will write the newline (and any other leading or trailing whitespace) into x.

So just as you needed to use x.trim().parse(), use x.trim() when comparing for the "exit" input.

        if x.trim() == "exit" {
2 Likes

Thank you very much!

Another approach could be to use .lines().next() instead of read_line().

use std::io;

fn main() {
    loop {
        println!("Check whether a number is even or odd.");
        println!(r#"Enter an integer or type "exit" to exit: "#);
        // comapred to `read_line()` using `lines().next()` creates the `String` for you
        // removes the line-break, and points out EOF more visibly
        // (`read_line` just returns Ok(0) for EOF)
        let x = io::stdin()
            .lines()
            .next()
            .expect("Unexpected EOF") // `None` stands for end-of-file
            .expect("Failed to read input"); // `Err(…)` would be other IO-related errors
        println!("Você digitou {}!", x);
        // without trim, this will still e.g. not match " exit " with spaces,
        // but maybe that's intended behavior
        if x == "exit" {
            break;
        } else {
            let mut x: u32 = match x.trim().parse() {
                Ok(num) => num,
                Err(_) => continue,
            };
            x = x % 2;
            if x == 0 {
                println!("The number is EVEN");
            } else {
                println!("The number is ODD");
            }
        }
    }
}
2 Likes

Cool! I will study its structure better to understand. Thank you for helping me!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.