use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::iter::Iterator;
fn main() -> std::io::Result<()> {
let file = File::open("input")?; // file is input
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents)?;
for i in contents.parse::<i32>() {
let i = i / 2;
println!("{}", i);
}
Ok(())
}
list of numbers:
50951
69212
119076
124303
95335
65069
109778
113786
124821
103423
128775
111918
138158
141455
92800
50908
107279
77352
129442
60097
84670
143682
104335
105729
87948
59542
81481
147508
For tiny examples like this, I'd read the entire string at once, then split it up on lines.
See also:
For tightly-controlled examples like this, I'd ignore errors occurring while parsing:
See also:
For fixed-input examples like this, I'd avoid opening the file at runtime at all, pushing the error to compile-time:
See also:
If I wanted to handle failures to parse but treat the iterator as if errors were impossible, I'd use
Itertools::process_results
:See also:
str::parse::<i32>
can only parse a single number at a time, so you will need to split the text first and then parse each number one by one. For example if you have one number per line and no extra whitespace, you can useBufRead::lines
to process the text line by line:As an extra bonus this avoids reading the whole file into memory, which can be important if the file is big.