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:
I get a vector of ints containing the above numbers as expected. But for a longer input like this:

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);

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();


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.


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