如何在Rust中从stdin中读取多行并一直读到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 a bb ccc dddd 5 eeeee dddd ccc bb a这是我的 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(())
}
lines().next()
,就像在C++版本中调用std::getline()
一样。请注意保持原意并使内容更加通俗易懂。 - Barmar