【问题标题】:How to read multiple lines from stdin until EOF?如何从标准输入读取多行直到 EOF?
【发布时间】: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 &lt; 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()

标签: c++ rust


【解决方案1】:

问题是你调用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(())
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2023-03-06
    • 2017-10-18
    • 1970-01-01
    • 2018-04-28
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多