Skip to content

Instantly share code, notes, and snippets.

@olafurw
Created December 21, 2022 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olafurw/c278bda47f46e74e212688f301626cc4 to your computer and use it in GitHub Desktop.
Save olafurw/c278bda47f46e74e212688f301626cc4 to your computer and use it in GitHub Desktop.
Parses numbers from a file and tells you which third they are in.
use std::io::BufRead;
use std::{env, io};
use std::error::Error;
use std::ffi::OsString;
use std::fs::File;
fn get_first_arg() -> Result<OsString, Box<dyn Error>> {
match env::args_os().nth(1) {
None => Err(From::from("expected 1 argument, but got none")),
Some(file_path) => Ok(file_path),
}
}
fn main() -> Result<(), Box<dyn Error>> {
let file_path = get_first_arg()?;
let file = File::open(file_path)?;
let reader = io::BufReader::new(file);
let mut segments: [u32; 3] = [0, 0, 0];
for line in reader.lines() {
let value = line.unwrap().parse::<u8>().unwrap();
if value < 34 {
segments[0] += 1;
} else if value < 67 {
segments[1] += 1;
} else {
segments[2] += 1;
}
}
println!("{}, {}, {}", segments[0], segments[1], segments[2]);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment