How do I read a single String from standard input?

后端 未结 1 946
天涯浪人
天涯浪人 2021-01-11 16:52

There isn\'t straightforward instruction on receiving a string as a variable in the std::io documentation, but I figured this should work:

use std::io;
let l         


        
相关标签:
1条回答
  • 2021-01-11 17:15

    Here's the code you need to do what you are trying (no comments on if it is a good way to go about it:

    use std::io::{self, BufRead};
    
    fn main() {
        let stdin = io::stdin();
        let line = stdin.lock()
            .lines()
            .next()
            .expect("there was no next line")
            .expect("the line could not be read");
    }
    

    If you want more control over where the line is read to, you can use Stdin::read_line. This accepts a &mut String to append to. With this, you can ensure that the string has a large enough buffer, or append to an existing string:

    use std::io::{self, BufRead};
    
    fn main() {
        let mut line = String::new();
        let stdin = io::stdin();
        stdin.lock().read_line(&mut line).expect("Could not read line");
        println!("{}", line)
    }
    
    0 讨论(0)
提交回复
热议问题