gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:55:22 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com