rust read lines from stdin and return a vec
To read lines from stdin and return a Vec
in Rust, you can use the std::io::stdin
module along with the BufRead
trait from the std::io
module. Here's an example of how you can achieve this:
use std::io::{self, BufRead};
fn read_lines() -> Vec<String> {
let stdin = io::stdin();
let lines = stdin.lock().lines().filter_map(Result::ok).collect();
lines
}
fn main() {
let lines = read_lines();
println!("{:?}", lines);
}
In this example, the read_lines
function reads the lines from stdin and returns them as a Vec<String>
. The stdin.lock().lines()
expression returns an iterator over the lines from stdin, and filter_map(Result::ok)
is used to filter out any errors and unwrap the lines. Finally, the collect
method is used to collect the lines into a Vec<String>
, which is then returned.
In the main
function, we call read_lines
to read the lines from stdin and store them in the lines
variable. Then, we simply print the lines
using println!("{:?}", lines)
for demonstration purposes.
You can customize this code according to your specific requirements. Let me know if you need any further assistance!