How to check for EOF in read_line in Rust 1.12?

2019-06-24 10:44发布

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.

标签: rust
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-06-24 11:05

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

查看更多
登录 后发表回答