Is there a way to use locked standard input and output in a constructor to live as long as the struct you're constructing?

后端 未结 2 1531
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 12:36

I\'m building a PromptSet that can ask a series of questions in a row. For testing reasons, it allows you to pass a reader and writer instead of using stdin & s

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-21 13:19

    Might be not really the answer to your question, but to a similar problem. Here's my solution.

    The main trick here is to call stdin.lock() for every single line.

    use std::io;
    use std::io::prelude::*;
    use std::io::Stdin;
    
    struct StdinWrapper {
        stdin: Stdin,
    }
    
    impl Iterator for StdinWrapper {
        type Item = String;
    
        fn next(&mut self) -> Option {
            let stdin = &self.stdin;
            let mut lines = stdin.lock().lines();
            match lines.next() {
                Some(result) => Some(result.expect("Cannot read line")),
                None => None,
            }
        }
    }
    
    /**
     * Callers of this method should not know concrete source of the strings.
     * It could be Stdin, a file, DB, or even aliens from SETI.
     */
    fn read() -> Box> {
        let stdin = io::stdin();
        Box::new(StdinWrapper { stdin })
    }
    
    fn main() {
        let lines = read();
    
        for line in lines {
            println!("{}", line);
        }
    }
    

提交回复
热议问题