Splitting string by comma breaks on one string but works on another

I'm trying to split the first line (a comma separated list of numbers) in my file into a vector of ints. For a smaller input file where the first line is:
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
I get a vector of ints containing the above numbers as expected. But for a longer input like this:
79,9,13,43,53,51,40,47,56,27,0,14,33,60,61,36,72,48,83,42,10,86,41,75,16,80,15,93,95,45,68,96,84,11,85,63,18,31,35,74,71,91,39,88,55,6,21,12,58,29,69,37,44,98,89,78,17,64,59,76,54,30,65,82,28,50,32,77,66,24,1,70,92,23,8,49,38,73,94,26,22,34,97,25,87,19,57,7,2,3,46,67,90,62,20,5,52,99,81,4

rust throws the following error at runtime:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }'

The following is my code:

pub fn foobar<R: BufRead>(mut file_it: R) -> i32 {
    let mut buf: String = String::new();
    let mut draws: Vec<i32> = vec![];
    match file_it.read_line(&mut buf) {
        Ok(num_bytes) => {
            draws = buf.split(",").map(|num| num.parse::<i32>().unwrap()).collect();
        }
        Err(e) => println!("Error reading bingo draws!"),
    }
    println!("{:?}", draws);
    0
}

From the error it would seem that there is some invalid character that cannot be converted to an int, however I cannot find anything like that in my longer input file. Any help to solve this issue is greatly appreciated!

Interesting, I tried the code with the input you gave and it worked fine. (playground)

Are you reading from a file? If so, there might be a newline character at the end (\n) that you can't see. I would suggested calling .trim() before parsing, which gets rid of any whitespace at the beginning or end of the string:

draws = buf.split(",").map(|num| num.trim().parse::<i32>().unwrap()).collect();

(playground)

Trimming is usually a good idea when parsing integers, as it's a common issue (easy to miss), easily resolved, and rather inexpensive to do.

2 Likes

I guess the longer file actually contains newline character at the end. Try .trim().parse() instead.

1 Like

trim() worked like a charm. Thank you @Cyborus04 and @Hyeonu!

1 Like