簡體   English   中英

如何從標准輸入讀取多行直到 EOF?

[英]How to read multiple lines from stdin until EOF?

如何從標准輸入讀取多行並前進到 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
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(())
}

問題是您兩次調用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(())
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM