Consider the following program, how do I detect EOF in stdin and break the loop?
use std::io;
use std::process;
fn main() {
let mut sum = 0;
loop {
let mut number_str = String::new();
match io::stdin().read_line(&mut number_str) {
Ok(n) => {},
Err(e) => { println!("ERROR: got '{}' when reading a line", e) }
}
match number_str.trim().parse::<i32>() {
Err(n) => {
println!("ERROR: Entered something that is not a number: '{}'",
number_str.trim_right());
process::exit(1)
},
Ok(n) => { sum += n }
}
}
}
Note: there is an identical question but the answer seems to be out of date anymore, which is why I added a version number in the question title.
From the documentation for
read_line
: