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

标签 rust

考虑以下程序,我如何检测标准输入中的 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.

关于rust - 如何在 Rust 1.12 的 read_line 中检查 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210691/

相关文章:

error-handling - 使用问号(?)运算符发生错误时如何登录文件?

rust - 调用 take 后如何继续使用迭代器?

rust - 捕获无法复制的移动值

rust - 柴油 : BoxableExpressions generic over a table and its joins?

linux - 如何在 Linux 下从特定接口(interface)发送 UDP 数据包?

rust - 为什么使用 Tcplistener 传入迭代器时 for 循环不退出

rust - 如何阅读基于 Tokio 的 Hyper 请求的整个主体?

rust - 如何创建 Rust 回调函数以传递给 FFI 函数?

generics - 即使 `AsRef` 存在足够长的时间,借用的值对于 `self` 结果来说也没有足够长的存在

rust - 不比较 Rust 中的字符串