How can I read a single line from stdin?

前端 未结 3 1601
南方客
南方客 2020-12-09 01:50

I\'m asking for the equivalent of fgets() in C.

let line = ...;
println!(\"You entered: {}\", line);

I\'ve read How to read us

3条回答
  •  北海茫月
    2020-12-09 02:10

    Read a single line from stdin:

        let mut line = String::new();
        std::io::stdin().read_line(&mut line)?; // including '\n'
    

    You may remove '\n' using line.trim_end()

    Read until EOF:

        let mut buffer = String::new();
        std::io::stdin().read_to_string(&mut buffer)?;
    

    Using implicit synchronization:

    use std::io;
    fn main() -> io::Result<()> {
        let mut line = String::new();
        io::stdin().read_line(&mut line)?;
    
        println!("You entered: {}", line);
        Ok(())
    }
    

    Using explicit synchronization:

    use std::io::{self, BufRead};
    
    fn main() -> io::Result<()> {
        let stdin = io::stdin();
        let mut handle = stdin.lock();
    
        let mut line = String::new();
        handle.read_line(&mut line)?;
    
        println!("You entered: {}", line);
        Ok(())
    }
    

    If you interested in the number of bytes e.g. n, use:
    let n = handle.read_line(&mut line)?;
    or
    let n = io::stdin().read_line(&mut line)?;

    Try this:

    use std::io;
    fn main() -> io::Result<()> {
        let mut line = String::new();
        let n = io::stdin().read_line(&mut line)?;
    
        println!("{} bytes read", n);
        println!("You entered: {}", line);
        Ok(())
    }
    

    See doc

提交回复
热议问题