【问题标题】:How to check for EOF in read_line in Rust 1.12?如何在 Rust 1.12 的 read_line 中检查 EOF?
【发布时间】:2016-12-19 01:15:29
【问题描述】:

考虑以下程序,我如何检测标准输入中的 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,但答案似乎已经过时了,这就是我在问题标题中添加版本号的原因。

【问题讨论】:

  • 我也欢迎在 cmets 中进行任何样式改进。

标签: rust


【解决方案1】:

来自documentation for read_line

如果此阅读器当前处于 EOF,则此函数将不会修改 buf 并将返回 Ok(n) 其中 n 是已读取的字节数。

【讨论】:

  • 所以在这种情况下它会是 Ok(0)?
  • @d33tah 是的,我相信是的。我无法想象任何其他数字会来自哪里,措辞有点模棱两可,不是吗?
  • 文档不是很清楚,但是如果剩余的输入是部分行会发生什么?它是作为一行返回,还是被丢弃?
猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 2011-01-16
  • 2012-06-18
  • 2019-04-23
相关资源
最近更新 更多