如何在Rust 1.12中的read_line中检查EOF?

考虑以下程序,如何在stdin中检测EOF并打破循环?

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

注意:有一个identical question,但答案似乎已经过时了,这就是为什么我在问题标题中添加了一个版本号.

最佳答案 从
documentation for read_line

If this reader is currently at EOF then this function will not modify buf and will return Ok(n) where n is the number of bytes which were read.

点赞