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