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
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);
}
}
There are few ways I can think of.
Read all the input into single String
let mut input = String::new();
io::stdin().read_to_end(&mut input);
Read lines into Vector
. This one doesn't panic
when reading a line fails, instead it skips that failed line.
let stdin = io::stdin();
let locked = stdin.lock();
let v: Vec<String> = locked.lines().filter_map(|line| line.ok()).collect();
Furthermore if you want to parse it:
After reading it into string do this. You can parse it to other collections that implements FromIterator
. Contained elements in the collection also must implement FromStr
. As long as the trait constraint satisfies you can change Vec to any Collection:FromIterator
, Collection<T: FromStr>
let v: Vec<i32> = "4 -42 232".split_whitespace().filter_map(|w| w.parse().ok()).collect();
Also you can use it on the StdinLock
let vv: Vec<Vec<i32>> = locked
.lines()
.filter_map(|l|
l.ok().map(|s|
s.split_whitespace().filter_map(|word| word.parse().ok()).collect()
)
)
.collect();
In Rust 1.0 and later, you can use the lines method on anything that implements the std::io::BufRead trait to obtain an iterator over lines in the input. You could also use read_line , but using the iterator is more likely what you'd want. Here is a version of the function in the question using iterators; see below for a more detailed explanation. (playground link)
use std::io;
use std::io::prelude::*;
pub fn read_lines() -> Vec<String> {
let stdin = io::stdin();
let stdin_lock = stdin.lock();
let vec = stdin_lock.lines().filter_map(|l| l.ok()).collect();
vec
}
And here's a version that is more like the C++ version in the question, but is not really the idiomatic way to do this in Rust (playground):
use std::io;
use std::io::prelude::*;
pub fn read_lines() -> Vec<String> {
let mut vec = Vec::new();
let mut string = String::new();
let stdin = io::stdin();
let mut stdin_lock = stdin.lock();
while let Ok(len) = stdin_lock.read_line(&mut string) {
if len > 0 {
vec.push(string);
string = String::new();
} else {
break
}
}
vec
}
To obtain something that implements BufRead
, which is needed to call lines()
or read_line()
, you call std::io::stdin() to obtain a handle to standard input, and then call lock() on the result of that to obtain exclusive control of the standard input stream (you must have exclusive control to obtain a BufRead
, because otherwise the buffering could produce arbitrary results if two threads were reading from stdin at once).
To collect the result into a Vec<String>
, you can use the collect method on an iterator. lines()
returns an iterator over Result<String>
, so we need to handle error cases in which a line could not be read; for this example, we just ignore errors with a filter_map
that just skips any errors.
The C++ like version uses read_line
, which appends the read line to a given string, and we then push the string into our Vec
. Because we transfer ownership of the string to the Vec
when we do that, and because read_line
would otherwise keep appending to the string
, we need to allocate a new string for each loop (this appears to be a bug in the original C++ version in the question, in which the same string is shared and so will keep accumulating every line). We use while let to continue to read until we hit an error, and we break if we ever read zero bytes which indicates the end of the input.
As of 17 April 2015 from mdcox
on the mozilla rust irc.
use std::io;
fn main() {
let mut stdin = io::stdin();
let input = &mut String::new();
loop {
input.clear();
stdin.read_line(input);
println!("{}", input);
}
}