How to read user input in Rust?

前端 未结 10 1694
情歌与酒
情歌与酒 2021-01-31 07:50

Editor\'s note: This question refers to parts of Rust that predate Rust 1.0, but the general concept is still valid in Rust 1.0.

I intend to

10条回答
  •  长情又很酷
    2021-01-31 08:21

    Rust 1.x (see documentation):

    use std::io;
    use std::io::prelude::*;
    
    fn main() {
        let stdin = io::stdin();
        for line in stdin.lock().lines() {
            println!("{}", line.unwrap());
        }
    }
    

    Rust 0.10–0.12 (see documentation):

    use std::io;
    
    fn main() {
        for line in io::stdin().lines() {
            print!("{}", line.unwrap());
        }
    }
    

    Rust 0.9 (see 0.9 documentation):

    use std::io;
    use std::io::buffered::BufferedReader;
    
    fn main() {
        let mut reader = BufferedReader::new(io::stdin());
        for line in reader.lines() {
            print(line);
        }
    }
    

    Rust 0.8:

    use std::io;
    
    fn main() {
        let lines = io::stdin().read_lines();
        for line in lines.iter() {
            println(*line);
        }
    }
    

    Rust 0.7:

    use std::io;
    
    fn main() {
        let lines = io::stdin().read_lines();
        for lines.iter().advance |line| {
            println(*line);
        }
    }
    

提交回复
热议问题