【发布时间】:2021-02-18 23:51:48
【问题描述】:
如何从标准输入读取多行并在 Rust 中前进到 EOF?我正在尝试将此 C++ 代码翻译成 Rust,但我失败了。
#include <iostream>
int main()
{
try {
std::string line;
while (std::getline(std::cin, line)) {
int length = std::stoi(line);
for (int i = 0; i < length; i++) {
std::string input;
std::getline(std::cin, input);
std::cout << input << std::endl;
}
}
} catch (std::invalid_argument const&) {
std::cout << "invalid input" << std::endl;
}
return 0;
}
程序接收到这个输入。它开始读取第一行,这是一个表示后面总行数的数字,然后尝试读取所有这些行并前进到下一个数字,直到它终止(或找到 EOF?)。
4 一个 bb ccc dddd 5 eeee dddd ccc bb 一个这是我的 Rust 代码。它可以编译,但似乎陷入了无限循环。我在终端中使用program < lines.txt 运行它。我做错了什么?
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let length: i32 = line.unwrap().trim().parse().unwrap();
for _ in 0..length {
let line = stdin.lock()
.lines()
.next()
.expect("there was no next line")
.expect("the line could not be read");
println!("{}", line);
}
}
Ok(())
}
【问题讨论】:
-
我不知道 Rust。但是外部循环已经循环了所有的行。所以内部循环可能也无法读取行。您应该在外循环中调用
lines().next(),就像在 C++ 版本中调用std::getline()。