Search code examples
rustnumbersoption-type

How can I parse the .nth() line in a file as an integer?


I am trying to figure out how to parse a specific line in a file as a u32 but I keep getting method not found in Option<String> when I try to parse a Option<String>.

Is there a way to parse it or am I approaching this wrong?

use std::io::{BufRead, BufReader};
use std::fs::File;

fn main() {
    let reader = BufReader::new(File::open("input").expect("Cannot open file"));
    let lines = reader.lines();
    let number: u32 = lines.nth(5).unwrap().ok().parse::<u32>();

    println!("{}", number);
}

Solution

  • You can't parse a number out of an Option<String>, since if it is None then there is nothing to parse. You must unwrap the Option first (or do proper error handling):

    use std::io::{BufRead, BufReader};
    use std::fs::File;
    
    fn main() {
        let reader = BufReader::new(File::open("input").expect("Cannot open file"));
        let number: u32 = reader.lines()
            .nth(5)
            .expect("input is not 5 lines long")
            .expect("could not read 5th line")
            .parse::<u32>()
            .expect("invalid number");
    
        println!("{}", number);
    }