如何从标准输入中读取多行直到EOF?

3

如何在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(())
}

3
我不了解Rust语言,但是外层循环已经在遍历所有行了。因此内层循环可能也无法读取行。你应该在外层循环中调用lines().next(),就像在C++版本中调用std::getline()一样。请注意保持原意并使内容更加通俗易懂。 - Barmar
1个回答

2
问题在于你两次调用stdin.lock()函数,会直接死锁。此外,你需要仅使用单个.lines()调用,因为其旨在消耗全部输入。幸运的是,这意味着我们只需将外部for循环重构为while循环:
use std::io::{self, BufRead};

fn main() -> io::Result<()> {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();

    while let Some(line) = lines.next() {
        let length: i32 = line.unwrap().trim().parse().unwrap();

        for _ in 0..length {
            let line = lines
                .next()
                .expect("there was no next line")
                .expect("the line could not be read");

            println!("{}", line);
        }
    }

    Ok(())
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接